public
Description: Ruby on Rails
Homepage: http://rubyonrails.org
Clone URL: git://github.com/rails/rails.git
Ensure Associations#sum returns 0 when no rows are returned. [#295 
state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
Jonathan Viney (author)
Sun Jun 01 20:00:15 -0700 2008
lifo (committer)
Mon Jun 02 04:50:44 -0700 2008
commit  4210d85a3f3ce4e980f473e9ed2becb84b58363b
tree    843c995a2c5852d03b7fbd0634424420d49a670f
parent  a980eb8c7734f14109d8c2a02a88dafdf682e0dc
...
71
72
73
74
 
75
76
77
...
265
266
267
268
269
 
 
270
271
272
...
71
72
73
 
74
75
76
77
...
265
266
267
 
 
268
269
270
271
272
0
@@ -71,7 +71,7 @@ module ActiveRecord
0
       #
0
       #   Person.sum('age')
0
       def sum(column_name, options = {})
0
-        calculate(:sum, column_name, options) || 0
0
+        calculate(:sum, column_name, options)
0
       end
0
 
0
       # This calculates aggregate values in the given column.  Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
0
@@ -265,8 +265,8 @@ module ActiveRecord
0
         def type_cast_calculated_value(value, column, operation = nil)
0
           operation = operation.to_s.downcase
0
           case operation
0
-            when 'count' then value.to_i
0
-            when 'avg'   then value && value.to_f
0
+            when 'count', 'sum' then value.to_i
0
+            when 'avg'          then value && value.to_f
0
             else column ? column.type_cast(value) : value
0
           end
0
         end
...
99
100
101
 
102
103
104
...
266
267
268
269
 
270
271
...
99
100
101
102
103
104
105
...
267
268
269
 
270
271
272
0
@@ -99,6 +99,7 @@ class CalculationsTest < ActiveRecord::TestCase
0
 
0
   def test_should_return_zero_if_sum_conditions_return_nothing
0
     assert_equal 0, Account.sum(:credit_limit, :conditions => '1 = 2')
0
+    assert_equal 0, companies(:rails_core).companies.sum(:id, :conditions => '1 = 2')
0
   end
0
 
0
   def test_should_group_by_summed_field_with_conditions
0
@@ -266,6 +267,6 @@ class CalculationsTest < ActiveRecord::TestCase
0
   end
0
 
0
   def test_should_sum_expression
0
-    assert_equal "636", Account.sum("2 * credit_limit")
0
+    assert_equal 636, Account.sum("2 * credit_limit")
0
   end
0
 end

Comments

lmarlow Mon Jun 02 10:53:50 -0700 2008

Calling #to_i on sums of float/decimal columns will give the wrong value.

lifo Mon Jun 02 11:36:22 -0700 2008

Thanks for pointing that out. Fixing…