开发者

Simple IRB Question regarding Count

I have a class called Deal.

Deal has vote_scores.

I would like to see how many vote_scores are in Deal that are greater than 2.

My guess :

for vote_scores > 2 in Deal count end

Doesn't really work :D

Edit:

I tried everyone's ideas. But note that :

Deal.vote_scores

Doesn't work because vote_scores is not an attribute of Deal, but rather an attribute of one of its Deals. So if I did this :

Deal.find(1).vote_scores

would return a #.

vote_scores is instantiated within the haml here:

.deal_summary{:id => "deal_#{deal_view.id}"}
.score
  = deal_view.vote_scores

in the mod开发者_如何学JAVAel here:

def vote_scores
  self.votes.inject(0){|sum, vote| sum + vote.value}
end


If you just want to know how many, the more efficient code will be:

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

This will be faster since the counting is done in sql rather than in ruby.

EDIT

Okay, we can try this:

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

This will return total number of deal object that has vote_scores > 2

Hopefully that is what you want to do.


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


deal = Deal.first #or whatever... Deal.find(10)
deal.votes.count :conditions => ['value > ?', 2]

for all Votes

Vote.count(:conditions => ['value > ?', 2'])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜