mirror of
https://github.com/github/rails.git
synced 2026-04-26 03:00:59 -04:00
Always return decimal average of integer fields
In previous version if database adapter (e.g. SQLite and Oracle) returned non-String calculated values then type_cast_using_column converted decimal average value of intefer field to integer value. Now operation parameter is always checked to decide which conversion of calculated value should be done.
This commit is contained in:
committed by
Aaron Patterson
parent
0616585619
commit
f4f4964ce0
@@ -282,15 +282,11 @@ module ActiveRecord
|
||||
end
|
||||
|
||||
def type_cast_calculated_value(value, column, operation = nil)
|
||||
if value.is_a?(String) || value.nil?
|
||||
case operation
|
||||
when 'count' then value.to_i
|
||||
when 'sum' then type_cast_using_column(value || '0', column)
|
||||
when 'average' then value.try(:to_d)
|
||||
else type_cast_using_column(value, column)
|
||||
end
|
||||
else
|
||||
type_cast_using_column(value, column)
|
||||
case operation
|
||||
when 'count' then value.to_i
|
||||
when 'sum' then type_cast_using_column(value || '0', column)
|
||||
when 'average' then value.try(:to_d)
|
||||
else type_cast_using_column(value, column)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -23,6 +23,11 @@ class CalculationsTest < ActiveRecord::TestCase
|
||||
assert_equal 53.0, value
|
||||
end
|
||||
|
||||
def test_should_return_decimal_average_of_integer_field
|
||||
value = Account.average(:id)
|
||||
assert_equal 3.5, value
|
||||
end
|
||||
|
||||
def test_should_return_nil_as_average
|
||||
assert_nil NumericData.average(:bank_balance)
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user