From 916ce930fa11aa5f718338cb04ee112fbb5d21d8 Mon Sep 17 00:00:00 2001 From: Ken Collins Date: Thu, 13 Nov 2008 10:52:49 -0500 Subject: [PATCH] Make sure any Fixnum returned by a DB sum is type cast to a Float before standard converstion to a BigDecimal. --- activerecord/lib/active_record/calculations.rb | 2 +- activerecord/test/cases/calculations_test.rb | 5 +++++ 2 files changed, 6 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index 6f4e02b..65512d5 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -286,7 +286,7 @@ module ActiveRecord case operation when 'count' then value.to_i when 'sum' then type_cast_using_column(value || '0', column) - when 'avg' then value && (value == 0 ? 0.0.to_d : value.to_d) + when 'avg' then value && (value.is_a?(Fixnum) ? value.to_f : value).to_d else type_cast_using_column(value, column) end end diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 0fa6150..8bd0dd0 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -25,6 +25,11 @@ class CalculationsTest < ActiveRecord::TestCase def test_should_return_nil_as_average assert_nil NumericData.average(:bank_balance) end + + def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal + assert_equal 0, NumericData.send(:type_cast_calculated_value, 0, nil, 'avg') + assert_equal 53.0, NumericData.send(:type_cast_calculated_value, 53, nil, 'avg') + end def test_should_get_maximum_of_field assert_equal 60, Account.maximum(:credit_limit) -- 1.6.0