This is almost answered in Difference Between find and Where with Relationships but not quite. (Notice how I subtly changed the question title!)
I do the query
a = Libation.where("user_id = 1" ) # gets 10 records
b = a.sum("count * weight") # Get right answer
c = Libation.where("user_id = 2" ) # gets 8 records
d = c.sum("count * weight") # Get right answer
Now I do
e = Libation.all # gets 18 records, good
f = e.sum("count * weight") # BOOM! I get
NoMethodError (undefined method `+' for #<Libation:0x3b91e88>):
Nuts. I tried to find relevant docs, but found little. Or I am not looking in the right place.
#wherereturns anActiveRecord::Relationobject, which you can them perform additional methods on (such as#sum). However,#allexecutes the query returns an array of results, so when you doe.sum(...)you’re trying to perform#sumon anArrayobject rather than anActiveRecord::Relationobject.You might try using
#scopedinstead: