Rails 4 query unique by single attribute

前端 未结 6 1309
我寻月下人不归
我寻月下人不归 2021-02-02 10:57

So this is more of an arel question than anything but here\'s what I am trying to do.

I have three objects lets say, called Items



        
6条回答
  •  春和景丽
    2021-02-02 11:38

    In Rails 4 try Items.all.to_a.uniq { |item| item.name }

    In Rails 3 you should be able to just do Items.uniq_by { |item| item.name }

    When you call uniq on an array, you can pass it a block to dictate how to determine uniqueness. In Rails 3 you used to be able to use uniq_by, but it became deprecated in Rails 4. So one method I found is to just convert the ActiveRecord Relation to an array and call uniq on that.

提交回复
热议问题