Skip to content

Commit

Permalink
Calculations: return nil average instead of 0 when there are no rows …
Browse files Browse the repository at this point in the history
…to average. Closes #8298.

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@6904 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information
jeremy committed May 30, 2007
1 parent b2681cc commit 1f80296
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 1 deletion.
2 changes: 2 additions & 0 deletions 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]
Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/calculations.rb
Expand Up @@ -265,7 +265,7 @@ def type_cast_calculated_value(value, column, operation = nil)
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
Expand Down
8 changes: 8 additions & 0 deletions activerecord/test/calculations_test.rb
Expand Up @@ -4,6 +4,10 @@

Company.has_many :accounts

class NumericData < ActiveRecord::Base
self.table_name = 'numeric_data'
end

class CalculationsTest < Test::Unit::TestCase
fixtures :companies, :accounts, :topics

Expand All @@ -17,6 +21,10 @@ def test_should_average_field
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
Expand Down

0 comments on commit 1f80296

Please sign in to comment.