Ruby-on-rails – the difference between “where” and “find”

This is almost answered in Difference Between find and Where with Relationships, but it is not complete. (Please note how I change the title of the question cleverly!)
I do a 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 #):

Nuts. I tried to find related documents, but found few. Or I can’t find a suitable place .

#where returns an ActiveRecord :: Relation object on which you can execute other methods ( For example #sum). However, #all executes the query to return an array of results, so when you execute e.sum(…), you are trying to execute #sum.

You can try #scoped instead:

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

This is almost in Difference Between f ind and Where with Relationships answer, but not complete. (Please note how I change the title of the question cleverly! )
I do a 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 #):

Nuts. I tried to find related documents, but found few .Or I can’t find a suitable place.

#where returns an ActiveRecord::Relation object on which you can perform other methods (e.g. #sum ). However, #all executes the query to return the result array, so when you execute e.sum(…), you try to execute #sum on the Array object instead of the ActiveRecord::Relation object.

You can try to use #scoped instead:

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

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3312 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.