Rails 4 query unique by single attribute

前端 未结 6 1308
我寻月下人不归
我寻月下人不归 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:20

    If you only need an array with the names, without the ID, you can do:

    Item.pluck(:name).uniq
    

    SQL query result:

    #=> SELECT `items`.`name` FROM `items`
    

    ** edit **

    The uniq is ran on the array of records. Be careful if you expect a lot of records. SQL Distinct is much faster.

    If so, use vee's answer above, with a map:

    Item.select('distinct name').map(:name)

提交回复
热议问题