aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTim Macfarlane <timmacfarlane@gmail.com>2012-08-24 10:08:36 +0100
committerTim Macfarlane <timmacfarlane@gmail.com>2012-10-15 22:31:05 +0100
commit51d6e21c966362ed63318d216913bcef504833a4 (patch)
treecbafbce249130e46f42b7ba590173dbe4c75403d
parent081f0ad413cd821f8dad5b334e7479ffdc0b037d (diff)
downloadrails-51d6e21c966362ed63318d216913bcef504833a4.tar.gz
rails-51d6e21c966362ed63318d216913bcef504833a4.tar.bz2
rails-51d6e21c966362ed63318d216913bcef504833a4.zip
ActiveRecord: sum expression returns string '0' for no records, fixed
-rw-r--r--activerecord/CHANGELOG.md5
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb2
-rw-r--r--activerecord/test/cases/calculations_test.rb4
3 files changed, 10 insertions, 1 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index f3362f81a3..ae86a0b94e 100644
--- a/activerecord/CHANGELOG.md
+++ b/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*
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index 7c43d844d0..6317004631 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -349,7 +349,7 @@ module ActiveRecord
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
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 6cb6c469d2..de4902f89a 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -378,6 +378,10 @@ class CalculationsTest < ActiveRecord::TestCase
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),