Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby-on-Rails: Selecting distinct values from the model

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?

like image 379
Bryan Wolfford Avatar asked Aug 01 '13 20:08

Bryan Wolfford


3 Answers

The .distinct option was added for rails 4 which is what the latest guides refer to.

Rails 2

If you are still on rails 2 you will need to use:

Client.select('distinct(name)')

Rails 3

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.

like image 181
Shadwell Avatar answered Nov 12 '22 12:11

Shadwell


There are some approaches:

  1. Rails way:

    Model.select(:name).distinct
    
  2. 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.

like image 42
Малъ Скрылевъ Avatar answered Nov 12 '22 10:11

Малъ Скрылевъ


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)
like image 10
David Aldridge Avatar answered Nov 12 '22 12:11

David Aldridge