diff options
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/CHANGELOG.md | 4 | ||||
-rw-r--r-- | activerecord/lib/active_record/relation/calculations.rb | 8 | ||||
-rw-r--r-- | activerecord/test/cases/calculations_test.rb | 10 |
3 files changed, 20 insertions, 2 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 99c78ad934..aff4982a05 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,7 @@ +* Use `Enumerable#sum` in `ActiveRecord::Relation` if a block is given. + + *Sean Griffin* + * Let `WITH` queries (Common Table Expressions) be explainable. *Vladimir Kochnev* diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 7a28a98721..29cc79db1b 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -70,8 +70,12 @@ module ActiveRecord # +calculate+ for examples with options. # # Person.sum(:age) # => 4562 - def sum(*args) - calculate(:sum, *args) + def sum(*args, &block) + if block_given? + to_a.sum(&block) + else + calculate(:sum, *args) + end end # This calculates aggregate values in the given column. Methods for count, sum, average, diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index cb4681109c..aa10817527 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -671,4 +671,14 @@ class CalculationsTest < ActiveRecord::TestCase developer.ratings.includes(comment: :post).where(posts: { id: 1 }).count end end + + def test_sum_uses_enumerable_version_when_block_is_given + block_called = false + relation = Client.all.load + + assert_no_queries do + assert_equal 0, relation.sum { block_called = true; 0 } + end + assert block_called + end end |