Rails 4 query unique by single attribute

Please try this:

Item.select('distinct name')

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.


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)