这几乎在 Difference Between find and Where with Relationships回答,但并不完全. (请注意我是如何巧妙地改变问题标题的!) 我做查询 a = Libation.where("user_id = 1" ) # gets 10 recordsb = a.sum("count * weight") #
我做查询
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
现在我做
e = Libation.all # gets 18 records, good f = e.sum("count * weight") # BOOM! I get NoMethodError (undefined method `+' for #<Libation:0x3b91e88>):
坚果.我试图找到相关的文档,但发现很少.或者我找不到合适的地方.
#where返回一个ActiveRecord :: Relation对象,您可以在其上执行其他方法(例如#sum).但是,#all执行查询返回结果数组,所以当你执行e.sum(…)时,你试图在Array对象而不是ActiveRecord :: Relation对象上执行#sum.您可以尝试使用#scoped代替:
e = Libation.scoped f = e.sum("count * weight")