mirror of https://github.com/rails/rails
Merge pull request #50674 from p8/activerecord/document-sum-with-block
Document `Calculations#count` and `Calculations#sum` block arguments …
This commit is contained in:
commit
beb6214bb0
|
@ -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)
|
||||
|
|
Loading…
Reference in New Issue