题
我有一个名为交易类。
交易vote_scores。
我想看到多少vote_scores是在交易是大于2。
我的猜测:
在交易有关vote_scores> 2 计数 端
并没有真正的工作:d
编辑:
我想大家的想法。但要注意:
Deal.vote_scores
不起作用,因为vote_scores不是交易的属性,而是它的优惠之一的属性。所以,如果我这样做:
Deal.find(1).vote_scores
将返回#。
vote_scores在HAML内这里实例:
.deal_summary{:id => "deal_#{deal_view.id}"}
.score
= deal_view.vote_scores
模型中的位置:
def vote_scores
self.votes.inject(0){|sum, vote| sum + vote.value}
end
解决方案
如果你只是想知道有多少,更高效的代码将是:
Deal.count(:conditions => ["vote_scores > ?", 2])
由于计数是SQL而非红宝石完成这会更快。
修改强>
好吧,我们可以试试这个:
Deal.find(:all).select {|e| e.vote_scores > 2}.count
这将返回交易对象的总数具有vote_scores> 2
希望这是你想要做什么。
其他提示
Deal.find(:所有,:条件=> [ “?vote_scores>”,2])。长度
deal = Deal.first #or whatever... Deal.find(10)
deal.votes.count :conditions => ['value > ?', 2]
对于所有的投票
Vote.count(:conditions => ['value > ?', 2'])
不隶属于 StackOverflow