0

我有一门课叫Deal。

交易有 vote_scores。

我想看看 Deal 中有多少 vote_scores 大于 2。

我猜 :

对于 vote_scores > 2 in Deal count end

真的不行:D

编辑:

我尝试了每个人的想法。但请注意:

Deal.vote_scores

不起作用,因为 vote_scores 不是 Deal 的属性,而是其中一个 Deal 的属性。所以如果我这样做:

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
4

3 回答 3

2

如果您只想知道有多少,更有效的代码将是:

Deal.count(:conditions => ["vote_scores > ?", 2])

这会更快,因为计数是在 sql 中而不是在 ruby​​ 中完成的。

编辑

好的,我们可以试试这个:

Deal.find(:all).select {|e| e.vote_scores > 2}.count

这将返回 vote_scores > 2 的交易对象总数

希望这就是你想要做的。

于 2010-05-13T13:39:53.617 回答
0
deal = Deal.first #or whatever... Deal.find(10)
deal.votes.count :conditions => ['value > ?', 2]

所有选票

Vote.count(:conditions => ['value > ?', 2'])
于 2010-05-13T14:53:08.877 回答
0

Deal.find(:all, :conditions => ["vote_scores > ?", 2]).length

于 2010-05-13T13:12:06.080 回答