Rails: how can I get unique values from column

99封情书 提交于 2019-12-28 03:29:06

问题


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%>

回答1:


Two more ways:

Product.select(:category).map(&:category).uniq

Product.uniq.pluck(:category)

For Rails >= 5.1 use:

Product.distinct.pluck(:category)



回答2:


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




回答3:


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"



回答4:


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




回答5:


Try this (in the rails console)

Product.group(:category)

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



回答6:


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)




回答7:


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 %>


来源:https://stackoverflow.com/questions/8369812/rails-how-can-i-get-unique-values-from-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!