views:

47

answers:

3

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 model here:

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

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

Tim Hoolihan
+2  A: 

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.

SamChandra
I tried that, and I added some comments above.
Trip
Take a look at my edited answer, is that what you want to do?
SamChandra
Sooo strange! This works on my local but on my live server, it returns that there is no method for 'count'..How strange is that? Thanks anyway!
Trip
Yes I got it! Beacuse its an array, you can't use count. But .size works!
Trip
You can always change count to size if you want to
SamChandra
this method is way less efficient than my answer below. it returns all records from the database before filtering by vote_scores.
Tim Hoolihan
A: 
deal = Deal.first #or whatever... Deal.find(10)
deal.votes.count :conditions => ['value > ?', 2]

for all Votes

Vote.count(:conditions => ['value > ?', 2'])
fl00r
Hmm.. undefined method 'votes'
Trip
of course undefined! I've updated comment. You should firstly define exact Deal for what you want to know votes count
fl00r
What if I want to find out the count of all of the deals' vote_scores above 2?
Trip
Vote.count(:conditions => ['value > ?', 2'])
fl00r