Skip to content

Commit beb6214

Browse files
authored
Merge pull request rails#50674 from p8/activerecord/document-sum-with-block
Document `Calculations#count` and `Calculations#sum` block arguments …
2 parents cdfca90 + 9ba7e53 commit beb6214

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

activerecord/lib/active_record/relation/calculations.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,16 @@ def truncate(name)
8181
#
8282
# Note: not all valid {Relation#select}[rdoc-ref:QueryMethods#select] expressions are valid #count expressions. The specifics differ
8383
# between databases. In invalid cases, an error from the database is thrown.
84+
#
85+
# When given a block, loads all records in the relation, if the relation
86+
# hasn't been loaded yet. Calls the block with each record in the relation.
87+
# Returns the number of records for which the block returns a truthy value.
88+
#
89+
# Person.count { |person| person.age > 21 }
90+
# # => counts the number of people older that 21
91+
#
92+
# Note: If there are a lot of records in the relation, loading all records
93+
# could result in performance issues.
8494
def count(column_name = nil)
8595
if block_given?
8696
unless column_name.nil?
@@ -148,6 +158,17 @@ def async_maximum(column_name)
148158
# #calculate for examples with options.
149159
#
150160
# Person.sum(:age) # => 4562
161+
#
162+
# When given a block, loads all records in the relation, if the relation
163+
# hasn't been loaded yet. Calls the block with each record in the relation.
164+
# Returns the sum of +initial_value_or_column+ and the block return
165+
# values:
166+
#
167+
# Person.sum { |person| person.age } # => 4562
168+
# Person.sum(1000) { |person| person.age } # => 5562
169+
#
170+
# Note: If there are a lot of records in the relation, loading all records
171+
# could result in performance issues.
151172
def sum(initial_value_or_column = 0, &block)
152173
if block_given?
153174
map(&block).sum(initial_value_or_column)

0 commit comments

Comments
 (0)