Rails: how can I get unique values from column

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

    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)

    0 讨论(0)
提交回复
热议问题