开发者

Select distinct active record

I have a model called Shops with an attribute called brands, brands is a text field and contains mult开发者_JAVA百科iple brands. What i would like to do is select all unique brands and display them sorted in alphabetic order

@brands = Shop.all(:select => 'distinct(brands)')

What to do from here?


If Shop#brands can hold multiple values like for example: "rony, hoke, fike", then I can reluctantly suggest doing something like this:

@brands = Shop.all(:select => 'brands').each { |s| 
  s.brands.split(',').map { |b| 
    b.strip.downcase
  }
}.flatten.uniq.sort

BUT, you should really think about your data model here to prevent such hackery. You couuld break out the brands into it's own table + model and do a many to many relationship with Shop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜