Skip to content

Commit

Permalink
Ensure Model.sum and Model.avg typecast appropriately. [#1066 state:r…
Browse files Browse the repository at this point in the history
…esolved]

Model.sum delegates typecasting to the column being summed. If that's not feasible, returns a string.
Model.avg always returns big decimal.
  • Loading branch information
lifo committed Oct 4, 2008
1 parent 6370ff3 commit 78feaf6
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
10 changes: 7 additions & 3 deletions activerecord/lib/active_record/calculations.rb
Expand Up @@ -278,11 +278,15 @@ def type_cast_calculated_value(value, column, operation = nil)
operation = operation.to_s.downcase
case operation
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
when 'sum' then type_cast_using_column(value || '0', column)
when 'avg' then value && value.to_d
else type_cast_using_column(value, column)
end
end

def type_cast_using_column(value, column)
column ? column.type_cast(value) : value
end
end
end
end
6 changes: 3 additions & 3 deletions activerecord/test/cases/calculations_test.rb
Expand Up @@ -18,8 +18,8 @@ def test_should_sum_field

def test_should_average_field
value = Account.average(:credit_limit)
assert_kind_of Float, value
assert_in_delta 53.0, value, 0.001
assert_kind_of BigDecimal, value
assert_equal BigDecimal.new('53.0'), value
end

def test_should_return_nil_as_average
Expand Down Expand Up @@ -273,7 +273,7 @@ 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

def test_count_with_from_option
Expand Down

0 comments on commit 78feaf6

Please sign in to comment.