Alex Rivera | Logout

Rails: select unique values from a column

Asked 2012-03-11T21:04:28.410
289

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.rating }

It selects, but don't print unique values, it prints all values, including the duplicates. And it's in the documentation: http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

Edit
Report

1 Answer

30
Model.select(:rating).uniq

This code works as 'DISTINCT' (not as Array#uniq) since rails 3.2

Above Rails 6 (?) it should be

Model.select(:rating).distinct
answered 2012-07-11T17:48:56.467

Your Answer