开发者

Query list of unique attributes

I created a Ruby array (Articles) with an attribute (category) containing repeating preset values (e.g. one of the fo开发者_如何学Gollowing: "Drink", "Main", "Side"). As result I'd like to get a list of all unique values of this category attribute.

I thought about something like

Article.all.category.uniq 

...but that didn't work. Here's an example array:

[#<Article id: 1, category: "Drink">, #<Article id: 2, category: "Main">, #<Article id: 3, category: "Drink">, #<Article id: 4, category: "Side">, #<Article id: 5, category: "Drink">, ] 

the content of the result list I am looking for should be in this case: "Drink", "Main", "Side"


Article.all.map {|a| a.category}.uniq

should do the job.


I'd do it like this:

Article.select("distinct category").map {|a| a.category}

rather than lucapette's answer, because that kind of operations are far slower in ruby than in a database.

My code example is assuming that you're using some kind of SQL database by the way. It would look different with other kinds of databases.


In Rails 3.2

Article.uniq.pluck(:category)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜