diff options
-rw-r--r-- | activerecord/CHANGELOG | 2 | ||||
-rw-r--r-- | activerecord/lib/active_record/calculations.rb | 2 | ||||
-rw-r--r-- | activerecord/test/cases/calculations_test.rb | 4 |
3 files changed, 7 insertions, 1 deletions
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 2a782f78ce..b4ebf3de48 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* ActiveRecord::Base#sum defaults to 0 if no rows are returned. Closes #11550 [kamal] + * Ensure that respond_to? considers dynamic finder methods. Closes #11538. [floehopper] * Ensure that save on parent object fails for invalid has_one association. Closes #10518. [Pratik] diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index 490c8f4712..64527ec3f0 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -71,7 +71,7 @@ module ActiveRecord # # Person.sum('age') def sum(column_name, options = {}) - calculate(:sum, column_name, options) + calculate(:sum, column_name, options) || 0 end # This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts. diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 0ed40b469d..a87fc26905 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -97,6 +97,10 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 105, Account.sum(:credit_limit, :conditions => 'firm_id = 6') end + def test_should_return_zero_if_sum_conditions_return_nothing + assert_equal 0, Account.sum(:credit_limit, :conditions => '1 = 2') + end + def test_should_group_by_summed_field_with_conditions c = Account.sum(:credit_limit, :conditions => 'firm_id > 1', :group => :firm_id) |