ActiveRecord’s sum or Rails’ Enumerable’s sum?
by Rabbit
product.inventory_transactions.sum(&:amount) # ArgumentError: wrong number of arguments...
Why? Because model.relationship returns a modified version of the Array class. The object returned acts very much like (if not identical to) calling Model.find, and accepts most (if not all) of find’s options.
So note that if you are calling model.relationship.sum, you either specify the attribute you’re interested in:
product.inventory_transactions.sum(:amount)
Or, if, for whatever reason, you want to use Enumerable’s sum method, you can convert to a standard array:
product.inventory_transactions.to_a.sum(&:amount)
What’s the difference? Model.relationship.sum is a database operation. model.relationship.to_a.sum is a pure Ruby operation.
Comments
[...] of a symbol trick that I don’t really understand (&:estimate_remaining). (Thanks to this blog for the .to_a trick)I was hoping to do something similar to another [...]