Rails: 如何从 column 获得惟一值

如何从表中的列获得唯一值? 例如,我有这个 Products 表:

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

这里我只想得到2个值-1 st _ cat 和2 nd _ cat:

<%Products.each do |p|%>
<%=p.category%>
<%end%>
87886 次浏览

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

Try this (in the rails console)

Product.group(:category)


Product.group(:category).each { |p| p.name }

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.

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"

Needed to get unique output and was trying the 'uniq' method unsuccessfully. Tried several solutions posted here unsuccessfully. I'm using devise which gives me access to the current_user method and working with two tables, one being a join (an item has_many :things).

This solution ultimately worked for me :

@current_user.things.select(:item_fk).distinct.each do |thing|
<%= thing.item.attribute %>
<% end %>

I suggest to use Products.all.distinct.pluck(:category) because uniq has been deprecated since rails 5 and it will be removed on rails 5.1

For postgres

<% Product.select("DISTINCT ON (category) *").each do |category|
<%= category %>
<%= name %>
<% end %>

Update

even better

<% Product.select(%(DISTINCT ON (category) "#{Product.table_name}".*)).each do |category|
<%= category %>
<%= name %>
<% end %>

because it can return wrong columns when you do joins (e.g. returns id column from joined table, but not products)

If you or anyone want to get two or more attributes from a table like products, based on a distinct feature of an attribute, only this solution will help you for Rails >= 5.1

distinct_products = Product.select("DISTINCT ON (category) *")


# it's an active record relation class.
> distinct_products.class
=> Product::ActiveRecord_Relation

N.B. Don't use .pluck() on the distinct_products. It will reselect from the products table and the distinct feature will not work anymore.