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

前端 未结 4 1330
攒了一身酷
攒了一身酷 2020-12-16 13:12

The docs: http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

Clearly state that:

query = Client.select(:name).distin         


        
相关标签:
4条回答
  • 2020-12-16 13:27

    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)
    
    0 讨论(0)
  • 2020-12-16 13:34

    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.

    0 讨论(0)
  • 2020-12-16 13:34

    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

    0 讨论(0)
  • 2020-12-16 13:36

    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.

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