sum(&:x) not working any more sum(&:x) not working any more ruby ruby

sum(&:x) not working any more


From the documentation:

sum(*args)

Calculates the sum of values on a given column. The value is returned with the same data type of the column, 0 if there's no row. See calculate for examples with options.

Person.sum(:age) # => 4562

it seems that your code should be without the &:

payments.sum(:price)


If you had run this in Rails 4.0, you would receive the following deprecation warning:

DEPRECATION WARNING: Calling #sum with a block is deprecated and will be removed in Rails 4.1. If you want to perform sum calculation over the array of elements, use ‘to_a.sum(&block)’.

This is referring to the method Relation#sum which previously worked in Rails 3.2 when given a block.

As others have answered, you either need to use payments.sum(:price) if price is a database column, or use payments.to_a.sum(&:price) if price is an instance method.


If payments is an ActiveRecord association, you can use the ActiveRecord::Calculations sum method instead:

payments.sum(:price)