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.