select vs distinct vs uniq?

时间:2016-08-11 06:34:26

标签: sql ruby-on-rails ruby activerecord padrino

我对Ruby的ActiveRecord uniq方法感到困惑。我正在使用它来尝试获取一个完整对象的数组,而不仅仅是一个特定的字段。

在我的Padrino应用程序脚本中,它将报纸名称和分数保存为Score对象,ActiveRecord Relation上的uniq方法属性不起作用,并且无论是否有SQL语法都不是不同的。谁能解释一下发生了什么?

class Score < ActiveRecord::Base

    def self.from_today
        self.where('created_at > ?', Date.today)
    end
end


scores = Score.from_today
scores.class      
=> Score::ActiveRecord_Relation 

scores.first
=> #<Score id: 123, score: -2.55, source: "Mail", created_at: "2016-08-11 04:29:24", updated_at: "2016-08-11 04:29:24">

scores.map(&:source) 
=> ["Mail", "Guardian", "Telegraph", "Independent", "Express", "Mail"]

scores.uniq(:source).count 
=> 6

scores.distinct(:source).count
=> 6

scores.select('distinct (SOURCE)').count
=> 5    #AHA, it works!

scores.select(:source).distinct
=> #<ActiveRecord::Relation [#<Score id: nil, source: "Telegraph">, #<Score id: nil, source: "Mail">, #<Score id: nil, source: "Independent">, #<Score id: nil, source: "Express">, #<Score id: nil, source: "Guardian">]>

        #oops, no it doesn't

1 个答案:

答案 0 :(得分:0)

在Rails 5中,distinct没有参数。在Rails 4.2中,参数仅为truefalse。当true时,返回不同的记录,当false不返回任何不同的记录时。在这种情况下,uniq只是distinct

的别名

对于Rails 4

scores.select(:source).distinct.count就是你想要的。这会将distinct限制为列source