Return raw value for numeric AVG calculation results
After this change `float`-typed database columns will return `Float` when aggregated with `AVG` (as expected and consistent with the behaviour of `MIN` and `MAX`). We keep returning `BigDecimal` for non-numeric column types which respond to `to_d`.
This commit is contained in:
parent
7b680baea2
commit
78b43e6694
@ -448,7 +448,11 @@ def type_cast_calculated_value(value, operation)
|
||||
when "sum"
|
||||
yield value || 0
|
||||
when "average"
|
||||
value&.respond_to?(:to_d) ? value.to_d : value
|
||||
if !value.is_a?(Numeric) && value&.respond_to?(:to_d)
|
||||
value.to_d
|
||||
else
|
||||
value
|
||||
end
|
||||
else # "minimum", "maximum"
|
||||
yield value
|
||||
end
|
||||
|
@ -59,6 +59,14 @@ def test_should_return_integer_average_if_db_returns_such
|
||||
assert_equal 3, value
|
||||
end
|
||||
|
||||
def test_should_return_float_average_if_db_returns_such
|
||||
NumericData.create!(temperature: 37.5)
|
||||
|
||||
value = NumericData.average(:temperature)
|
||||
assert_instance_of Float, value
|
||||
assert_equal 37.5, value
|
||||
end
|
||||
|
||||
def test_should_return_nil_as_average
|
||||
assert_nil NumericData.average(:bank_balance)
|
||||
end
|
||||
|
Loading…
Reference in New Issue
Block a user