rtfminc
rtfminc

Reputation: 6363

Difference between "where" and "find"

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.

Upvotes: 3

Views: 1902

Answers (2)

Andrei S
Andrei S

Reputation: 6516

doing Model.where(condition) returns an Active Relation, so when you do a = Libation.where(...) you don't get an array, but an Active Relation on which you can chain other methods as you do below b = a.sum(...)

Libation.all returns an array of objects, actually executing the query to the database (by using where, the query is called only when you try to iterate for example over the returned result)

Upvotes: 1

Dylan Markow
Dylan Markow

Reputation: 124419

#where returns an ActiveRecord::Relation object, which you can them perform additional methods on (such as #sum). However, #all executes the query returns an array of results, so when you do e.sum(...) you're trying to perform #sum on an Array object rather than an ActiveRecord::Relation object.

You might try using #scoped instead:

e = Libation.scoped
f = e.sum("count * weight")

Upvotes: 6

Related Questions