Skip to content
Browse files

Merge pull request #7439 from featurist/master

ActiveRecord: sum expression returns string '0' for no records, fixed
  • Loading branch information...
2 parents 081f0ad + 51d6e21 commit 0a78417386958e849a32e3b8def23e3e28f1e5b0 @tenderlove tenderlove committed Oct 15, 2012
View
5 activerecord/CHANGELOG.md
@@ -906,3 +906,8 @@
*Aaron Patterson*
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
2 activerecord/lib/active_record/relation/calculations.rb
@@ -349,7 +349,7 @@ def column_for(field)
def type_cast_calculated_value(value, column, operation = nil)
case operation
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
else type_cast_using_column(value, column)
end
View
4 activerecord/test/cases/calculations_test.rb
@@ -378,6 +378,10 @@ def test_should_sum_expression
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
assert_equal Company.count(:all), Company.from('companies').count(:all)
assert_equal Account.where("credit_limit = 50").count(:all),

0 comments on commit 0a78417

Please sign in to comment.
Something went wrong with that request. Please try again.