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
dhh (committer)
Mon Jun 02 16:52:15 -0700 2008
commit  f657371fc372101c2eec30f66417e972af265a4c
tree    5e5f4742fb3557fe5a9fec9d2bd1ddd01c514453
parent  4d850e43d751bff95e25bcd36f7d660ba1d43f2a
...
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