Skip to content

Commit

Permalink
Ensure AR#sum result is typecasted properly
Browse files Browse the repository at this point in the history
  • Loading branch information
lifo authored and dhh committed Jun 2, 2008
1 parent 2af6489 commit 604a588
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
5 changes: 3 additions & 2 deletions activerecord/lib/active_record/calculations.rb
Expand Up @@ -265,8 +265,9 @@ def column_for(field)
def type_cast_calculated_value(value, column, operation = nil)
operation = operation.to_s.downcase
case operation
when 'count', 'sum' then value.to_i
when 'avg' then value && value.to_f
when 'count' then value.to_i
when 'sum' then value =~ /\./ ? value.to_f : value.to_i
when 'avg' then value && value.to_f
else column ? column.type_cast(value) : value
end
end
Expand Down
5 changes: 5 additions & 0 deletions activerecord/test/cases/calculations_test.rb
Expand Up @@ -102,6 +102,11 @@ def test_should_return_zero_if_sum_conditions_return_nothing
assert_equal 0, companies(:rails_core).companies.sum(:id, :conditions => '1 = 2')
end

def test_sum_should_return_valid_values_for_decimals
NumericData.create(:bank_balance => 19.83)
assert_equal 19.83, NumericData.sum(:bank_balance)
end

def test_should_group_by_summed_field_with_conditions
c = Account.sum(:credit_limit, :conditions => 'firm_id > 1',
:group => :firm_id)
Expand Down

0 comments on commit 604a588

Please sign in to comment.