2016-08-11 32 views
0

我对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 
+0

那么你想要什么结果集? –

+0

我正在使用它来尝试获取完整对象的数组,而不仅仅是特定的字段。 –

回答

0

In Rails 5 distinct has no parameter。在Rails 4.2中,参数仅为truefalse。当true,返回不同的记录,当false返回无明显记录。 uniq在这种情况下只为distinct

所以对于Rails的一个别名4

scores.select(:source).distinct.count是你想要的。这限制distinctsource

+0

但它不会返回完整的对象,会吗? –

+0

'scores.select(:source).distinct'不返回完整的对象。只有填充了源列的对象。因为你不能说出你想要的其他属性的值。例如,具有'source' Mail的对象的值应该是'created_at'?记录123或其他值? – slowjack2k

+0

那么如何找回所有具有唯一:source属性的Score对象? –