Skip to content
Browse files

Ensure Associations#sum returns 0 when no rows are returned. [#295 st…

…ate:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information...
1 parent a980eb8 commit 4210d85a3f3ce4e980f473e9ed2becb84b58363b Jonathan Viney committed with lifo Jun 2, 2008
Showing with 5 additions and 4 deletions.
  1. +3 −3 activerecord/lib/active_record/calculations.rb
  2. +2 −1 activerecord/test/cases/calculations_test.rb
View
6 activerecord/lib/active_record/calculations.rb
@@ -71,7 +71,7 @@ def maximum(column_name, options = {})
#
# 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,8 +265,8 @@ def column_for(field)
def type_cast_calculated_value(value, column, operation = nil)
operation = operation.to_s.downcase
case operation
- when 'count' then value.to_i
- when 'avg' then value && value.to_f
+ when 'count', 'sum' then value.to_i
+ when 'avg' then value && value.to_f
else column ? column.type_cast(value) : value
end
end
View
3 activerecord/test/cases/calculations_test.rb
@@ -99,6 +99,7 @@ def test_should_sum_field_with_conditions
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 @@ def test_count_with_too_many_parameters_raises
end
def test_should_sum_expression
- assert_equal "636", Account.sum("2 * credit_limit")
+ assert_equal 636, Account.sum("2 * credit_limit")
end
end

2 comments on commit 4210d85

@lmarlow
lmarlow commented on 4210d85 Jun 2, 2008

Calling #to_i on sums of float/decimal columns will give the wrong value.

@lifo
Ruby on Rails member
lifo commented on 4210d85 Jun 2, 2008

Thanks for pointing that out. Fixing…

Please sign in to comment.
Something went wrong with that request. Please try again.