From e7bec4e435d05eb517f515a4661186ce8d088238 Mon Sep 17 00:00:00 2001 From: Bogdan Gusiev Date: Tue, 5 Jul 2011 14:36:20 +0300 Subject: Fixed AR::Relation#sum compatibility with Array#sum In order make Relation behavior closer to Array Made Relation#sum to accept block and delegate it to Array#sum --- activerecord/lib/active_record/relation/calculations.rb | 8 ++++++-- activerecord/test/cases/calculations_test.rb | 4 ++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 9c5f603c01..0ac821b2d7 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -89,8 +89,12 @@ module ActiveRecord # +calculate+ for examples with options. # # Person.sum('age') # => 4562 - def sum(column_name, options = {}) - calculate(:sum, column_name, options) + def sum(*args) + if block_given? + self.to_a.sum(*args) {|*block_args| yield(*block_args)} + else + calculate(:sum, *args) + end end # This calculates aggregate values in the given column. Methods for count, sum, average, diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 56f6d795b6..224b3f3d1f 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -397,6 +397,10 @@ class CalculationsTest < ActiveRecord::TestCase Account.sum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50") end + def test_sum_array_compatibility + assert_equal Account.sum(:credit_limit), Account.sum(&:credit_limit) + end + def test_average_with_from_option assert_equal Account.average(:credit_limit), Account.average(:credit_limit, :from => 'accounts') assert_equal Account.average(:credit_limit, :conditions => "credit_limit > 50"), -- cgit v1.2.3