From 5c3667be4f35b2ac247701d7bd4e4ebfb0c6f116 Mon Sep 17 00:00:00 2001 From: Ken Collins Date: Thu, 3 Feb 2011 15:07:03 -0500 Subject: [PATCH] The type_cast_calculated_value method will trust DB types before casting to a BigDecimal. --- .../lib/active_record/relation/calculations.rb | 2 +- activerecord/test/cases/calculations_test.rb | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 54a8b05..848b7d3 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -276,7 +276,7 @@ module ActiveRecord 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) + when 'average' then value.respond_to?(:to_d) ? value.to_d : value 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 644c9cb..3121f16 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -28,6 +28,12 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 3.5, value end + def test_should_return_integer_average_if_db_returns_such + Account.connection.stubs :select_value => 3 + value = Account.average(:id) + assert_equal 3, value + end + def test_should_return_nil_as_average assert_nil NumericData.average(:bank_balance) end -- 1.7.2.2