Merge pull request #50674 from p8/activerecord/document-sum-with-block

Document `Calculations#count` and `Calculations#sum` block arguments …
This commit is contained in:
Rafael Mendonça França 2024-01-09 19:08:04 -05:00 committed by GitHub
commit beb6214bb0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 21 additions and 0 deletions

View File

@ -81,6 +81,16 @@ module ActiveRecord
#
# Note: not all valid {Relation#select}[rdoc-ref:QueryMethods#select] expressions are valid #count expressions. The specifics differ
# between databases. In invalid cases, an error from the database is thrown.
#
# When given a block, loads all records in the relation, if the relation
# hasn't been loaded yet. Calls the block with each record in the relation.
# Returns the number of records for which the block returns a truthy value.
#
# Person.count { |person| person.age > 21 }
# # => counts the number of people older that 21
#
# Note: If there are a lot of records in the relation, loading all records
# could result in performance issues.
def count(column_name = nil)
if block_given?
unless column_name.nil?
@ -148,6 +158,17 @@ module ActiveRecord
# #calculate for examples with options.
#
# Person.sum(:age) # => 4562
#
# When given a block, loads all records in the relation, if the relation
# hasn't been loaded yet. Calls the block with each record in the relation.
# Returns the sum of +initial_value_or_column+ and the block return
# values:
#
# Person.sum { |person| person.age } # => 4562
# Person.sum(1000) { |person| person.age } # => 5562
#
# Note: If there are a lot of records in the relation, loading all records
# could result in performance issues.
def sum(initial_value_or_column = 0, &block)
if block_given?
map(&block).sum(initial_value_or_column)