Rails: how can I get unique values from column

前端 未结 7 1394
礼貌的吻别
礼貌的吻别 2020-12-02 09:59

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_c         


        
相关标签:
7条回答
  • 2020-12-02 10:03

    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 %>
    
    0 讨论(0)
  • 2020-12-02 10:08

    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

    0 讨论(0)
  • 2020-12-02 10:11

    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"
    
    0 讨论(0)
  • 2020-12-02 10:18

    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

    0 讨论(0)
  • 2020-12-02 10:20

    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.

    0 讨论(0)
  • 2020-12-02 10:22

    Try this (in the rails console)

    Product.group(:category)
    
    Product.group(:category).each { |p| p.name }
    
    0 讨论(0)
提交回复
热议问题