Rails: how can I get unique values from column

前端 未结 7 1438
礼貌的吻别
礼貌的吻别 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: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.

提交回复
热议问题