Rails: select unique values from a column

后端 未结 13 1839
甜味超标
甜味超标 2020-11-27 09:38

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.rat         


        
相关标签:
13条回答
  • 2020-11-27 09:47
    Model.pluck("DISTINCT column_name")
    
    0 讨论(0)
  • 2020-11-27 09:56
    Model.uniq.pluck(:rating)
    
    # SELECT DISTINCT "models"."rating" FROM "models"
    

    This has the advantages of not using sql strings and not instantiating models

    0 讨论(0)
  • 2020-11-27 09:56
    Model.select(:rating).distinct
    
    0 讨论(0)
  • 2020-11-27 09:58

    This works too.

    Model.pluck("DISTINCT rating")
    
    0 讨论(0)
  • 2020-11-27 10:00

    If you want to also select extra fields:

    Model.select('DISTINCT ON (models.ratings) models.ratings, models.id').map { |m| [m.id, m.ratings] }
    
    0 讨论(0)
  • 2020-11-27 10:03

    Some answers don't take into account the OP wants a array of values

    Other answers don't work well if your Model has thousands of records

    That said, I think a good answer is:

        Model.uniq.select(:ratings).map(&:ratings)
        => "SELECT DISTINCT ratings FROM `models` " 
    

    Because, first you generate a array of Model (with diminished size because of the select), then you extract the only attribute those selected models have (ratings)

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