Rails: how can I get unique values from column

Oleg Pasko picture Oleg Pasko · Dec 3, 2011 · Viewed 75k times · Source

How can I get unique values from column in the table? For example, I have this Products table:

ID NAME CATEGORY
1 name1 1st_cat
2 name2 2nd_cat
3 name3 1st_cat

Here I want to get only 2 values - 1st_cat and 2nd_cat:

<%Products.each do |p|%>
<%=p.category%>
<%end%>

Answer

user664833 picture user664833 · Jul 28, 2012

Two more ways:

Product.select(:category).map(&:category).uniq # Ruby does the work

Product.uniq.pluck(:category) # DB does the work (superior)

For Rails >= 5.1 use:

Product.distinct.pluck(:category) # DB does the work (superior)

...because Relation#uniq was deprecated.