diff options
author | Raimonds Simanovskis <raimonds.simanovskis@gmail.com> | 2011-01-10 18:55:32 +0200 |
---|---|---|
committer | Aaron Patterson <aaron.patterson@gmail.com> | 2011-01-10 15:51:32 -0800 |
commit | f4f4964ce0a05cac38bbff3b308ac558228bad29 (patch) | |
tree | abfdd44377a721f46ef38aea35f68e4f55654830 | |
parent | 06165856196ac17b87163d146abea46019b17032 (diff) | |
download | rails-f4f4964ce0a05cac38bbff3b308ac558228bad29.tar.gz rails-f4f4964ce0a05cac38bbff3b308ac558228bad29.tar.bz2 rails-f4f4964ce0a05cac38bbff3b308ac558228bad29.zip |
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.
-rw-r--r-- | activerecord/lib/active_record/relation/calculations.rb | 14 | ||||
-rw-r--r-- | activerecord/test/cases/calculations_test.rb | 5 |
2 files changed, 10 insertions, 9 deletions
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index e9e451ec5c..b75a65e3ca 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -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 diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 5cb8485b4b..644c9cb528 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -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 |