Rails: select unique values from a column

后端 未结 13 1838
甜味超标
甜味超标 2020-11-27 09:38

I already have a working solution, but I would really like to know why this doesn\'t work:

ratings = Model.select(:rating).uniq
ratings.each { |r| puts r.rat         


        
相关标签:
13条回答
  • 2020-11-27 10:06

    If you're going to use Model.select, then you might as well just use DISTINCT, as it will return only the unique values. This is better because it means it returns less rows and should be slightly faster than returning a number of rows and then telling Rails to pick the unique values.

    Model.select('DISTINCT rating')
    

    Of course, this is provided your database understands the DISTINCT keyword, and most should.

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