Reputation: 2192
The docs: http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields
Clearly state that:
query = Client.select(:name).distinct
# => Returns unique names
However, when I try that in my controller, I get the following error:
undefined method `distinct' for #<ActiveRecord::Relation:0xb2f6f2cc>
To be clear, I want the distinct names, like ['George', 'Brandon'], not the clients actual records. Is there something that I am missing?
Upvotes: 34
Views: 90209
Reputation: 34784
If you are still on rails 2 you will need to use:
Client.select('distinct(name)')
If you are on Rails 3 you will need to use:
Client.select(:name).uniq
If you look at the equivalent section of the rails 3 guide you can see the difference between the two versions.
The .distinct
option was added for rails 4 which is what the latest guides refer to.
Client.select(:name).distinct
Upvotes: 55
Reputation: 16514
There are some approaches:
Rails way:
Model.select(:name).distinct
Semi-rails way
Model.select("DISTINCT ON(models.name) models.*")
The second allows you to select the first record uniqued by name, but in the whole matter, not only names.
Upvotes: 15
Reputation: 29174
This will work for Rails 2 (pretty old rails I know!), 3 and 4.
Client.select('distinct(name)')
This will actually use the SQL select distinct statement
SELECT distinct name FROM clients
Upvotes: 4
Reputation: 52386
If you do not want ActiveRecord::Relations returned, just an array of the names as strings, then use:
Client.distinct.pluck(:name)
To get an ordered result set:
Client.order(:name).distinct.pluck(:name)
Upvotes: 16