我对Ruby的ActiveRecord uniq方法感到困惑。我正在使用它来试图找回一组完整的对象,而不仅仅是一个特定的字段。select vs distinct vs uniq?
在我的Padrino应用程序脚本中,它将报表名称和分数保存为Score对象,ActiveRecord Relation中的uniq方法by属性不起作用,并且两者都不是独立的,有或没有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
那么你想要什么结果集? –
我正在使用它来尝试获取完整对象的数组,而不仅仅是特定的字段。 –