Rails 4 query unique by single attribute

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

    0 讨论(0)
  • 2021-02-02 11:24

    I can't comment on posts yet, so, putting this as another answer for the question.

    In case of someone still searches for this, @BananaNeil's answer is correct. However, putting distinct in select didn't work for me (Rails 5.2.2). Separating these two did fix my problem.

    klass.where(
      # Your query or whatever
    ).distinct.select('on (attribute) *')
    
    0 讨论(0)
  • 2021-02-02 11:29

    If you want to get the entire model back, but still maintain uniqueness, you can use this:

    Item.select('distinct on (name) *')
    

    I've only tested this with a Postgres database. It may or may not work with mysql.

    0 讨论(0)
  • 2021-02-02 11:33

    For Mysql, your can use group with ONLY_FULL_GROUP_BY disabled,

    Item.group(:name).to_sql
    => "SELECT `items`.* FROM `items`  GROUP BY name"
    

    See Is there ANY_VALUE capability for mysql 5.6?

    0 讨论(0)
  • 2021-02-02 11:37

    Please try this:

    Item.select('distinct name')
    
    0 讨论(0)
  • 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.

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