我對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
那麼你想要什麼結果集? –
我正在使用它來嘗試獲取完整對象的數組,而不僅僅是特定的字段。 –