From daa4b1b2e076e0666165c7be70139900ce50cb72 Mon Sep 17 00:00:00 2001 From: Jonathan Viney Date: Mon, 2 Jun 2008 15:00:15 +1200 Subject: [PATCH] Ensure sum on associations returns 0 when no rows are returned. --- activerecord/lib/active_record/calculations.rb | 4 ++-- activerecord/test/cases/calculations_test.rb | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index 10e8330..786151b 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) || 0 + calculate(:sum, column_name, options) end # This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts. @@ -265,7 +265,7 @@ module ActiveRecord def type_cast_calculated_value(value, column, operation = nil) operation = operation.to_s.downcase case operation - when 'count' then value.to_i + when 'count', 'sum' then value.to_i when 'avg' then value && value.to_f else column ? column.type_cast(value) : value end diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index a87fc26..5cf655f 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -99,6 +99,7 @@ class CalculationsTest < ActiveRecord::TestCase def test_should_return_zero_if_sum_conditions_return_nothing assert_equal 0, Account.sum(:credit_limit, :conditions => '1 = 2') + assert_equal 0, companies(:rails_core).companies.sum(:id, :conditions => '1 = 2') end def test_should_group_by_summed_field_with_conditions @@ -266,6 +267,6 @@ class CalculationsTest < ActiveRecord::TestCase end def test_should_sum_expression - assert_equal "636", Account.sum("2 * credit_limit") + assert_equal 636, Account.sum("2 * credit_limit") end end -- 1.5.2.5 From 46a5057503c1b35b23e55d71a2285b577ca21f03 Mon Sep 17 00:00:00 2001 From: Jonathan Viney Date: Mon, 2 Jun 2008 15:02:38 +1200 Subject: [PATCH] Ensure sum on associations returns 0 when no rows are returneda. --- activerecord/lib/active_record/calculations.rb | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index 786151b..889b784 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -266,7 +266,7 @@ module ActiveRecord operation = operation.to_s.downcase case operation when 'count', 'sum' then value.to_i - when 'avg' then value && value.to_f + when 'avg' then value && value.to_f else column ? column.type_cast(value) : value end end -- 1.5.2.5