1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

ActiveRecord: sum expression returns string '0' for no records, fixed

This commit is contained in:
Tim Macfarlane 2012-08-24 10:08:36 +01:00
parent 081f0ad413
commit 51d6e21c96
3 changed files with 10 additions and 1 deletions

View file

@ -906,3 +906,8 @@
*Aaron Patterson* *Aaron Patterson*
Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activerecord/CHANGELOG.md) for previous changes. Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activerecord/CHANGELOG.md) for previous changes.
* Fix bug where sum(expression) returns string '0' for no matching records
Fixes #7439
*Tim Macfarlane*

View file

@ -349,7 +349,7 @@ module ActiveRecord
def type_cast_calculated_value(value, column, operation = nil) def type_cast_calculated_value(value, column, operation = nil)
case operation case operation
when 'count' then value.to_i when 'count' then value.to_i
when 'sum' then type_cast_using_column(value || '0', column) when 'sum' then type_cast_using_column(value || 0, column)
when 'average' then value.respond_to?(:to_d) ? value.to_d : value when 'average' then value.respond_to?(:to_d) ? value.to_d : value
else type_cast_using_column(value, column) else type_cast_using_column(value, column)
end end

View file

@ -378,6 +378,10 @@ class CalculationsTest < ActiveRecord::TestCase
end end
end end
def test_sum_expression_returns_zero_when_no_records_to_sum
assert_equal 0, Account.where('1 = 2').sum("2 * credit_limit")
end
def test_count_with_from_option def test_count_with_from_option
assert_equal Company.count(:all), Company.from('companies').count(:all) assert_equal Company.count(:all), Company.from('companies').count(:all)
assert_equal Account.where("credit_limit = 50").count(:all), assert_equal Account.where("credit_limit = 50").count(:all),