From 1f802968c5a803f649fc27c7295b01aef3af6514 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 30 May 2007 06:57:04 +0000 Subject: [PATCH] Calculations: return nil average instead of 0 when there are no rows to average. Closes #8298. git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@6904 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activerecord/CHANGELOG | 2 ++ activerecord/lib/active_record/calculations.rb | 2 +- activerecord/test/calculations_test.rb | 8 ++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 8d12f3ab49..caddb6412a 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Calculations: return nil average instead of 0 when there are no rows to average. #8298 [davidw] + * acts_as_nested_set: direct_children is sorted correctly. #4761 [Josh Peek, rails@33lc0.net] * Raise an exception if both attr_protected and attr_accessible are declared. #8507 [stellsmi] diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index a54ef468e0..09c0c979e6 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -265,7 +265,7 @@ module ActiveRecord operation = operation.to_s.downcase case operation when 'count' then value.to_i - when 'avg' then value.to_f + when 'avg' then value && value.to_f else column ? column.type_cast(value) : value end end diff --git a/activerecord/test/calculations_test.rb b/activerecord/test/calculations_test.rb index e450c0a917..22ef78ce40 100644 --- a/activerecord/test/calculations_test.rb +++ b/activerecord/test/calculations_test.rb @@ -4,6 +4,10 @@ require 'fixtures/topic' Company.has_many :accounts +class NumericData < ActiveRecord::Base + self.table_name = 'numeric_data' +end + class CalculationsTest < Test::Unit::TestCase fixtures :companies, :accounts, :topics @@ -17,6 +21,10 @@ class CalculationsTest < Test::Unit::TestCase assert_in_delta 53.0, value, 0.001 end + def test_should_return_nil_as_average + assert_nil NumericData.average(:bank_balance) + end + def test_should_get_maximum_of_field assert_equal 60, Account.maximum(:credit_limit) end