Use Enumerable#sum
on ActiveRecord::Relation
when a block is given
This matches our behavior in other cases where useful enumerable methods might have a different definition in `Relation`. Wanting to actually enumerate over the records in this case is completely reasonable, and wanting `.sum` is reasonable for the same reason it is on `Enumerable` in the first place.
This commit is contained in:
parent
40bdf0dd4c
commit
7d14bd3ff5
@ -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*
|
||||
|
@ -70,8 +70,12 @@ def maximum(column_name)
|
||||
# +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,
|
||||
|
@ -671,4 +671,14 @@ def test_should_reference_correct_aliases_while_joining_tables_of_has_many_throu
|
||||
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
|
||||
|
Loading…
Reference in New Issue
Block a user