Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query list of unique attributes

I created a Ruby array (Articles) with an attribute (category) containing repeating preset values (e.g. one of the following: "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"

like image 799
Bernd Avatar asked Sep 19 '11 22:09

Bernd


2 Answers

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

should do the job.

like image 73
lucapette Avatar answered Oct 03 '22 00:10

lucapette


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.

like image 21
Frost Avatar answered Oct 03 '22 02:10

Frost