Rails: how can I get unique values from column

I think you can do this:

<% Products.select("DISTINCT(CATEGORY)").each do |p| %>
<%= p.category %>
<% end %>

Source: http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields


This does all the work in the database server. The result is a simple array.

<% Product.distinct(:category).pluck(:category).each do |category|
    <%= category %>
<% end %>

Rails will generate SQL that works on any database (Postgres, MySQL, etc).

SELECT DISTINCT "products"."category" FROM "products"

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.