From 9ba7e53f688ae3e8f30336d9fb85d0be51575630 Mon Sep 17 00:00:00 2001 From: Petrik Date: Thu, 4 Jan 2024 11:05:29 +0100 Subject: [PATCH] Document `Calculations#count` and `Calculations#sum` block arguments [ci-skip] --- .../active_record/relation/calculations.rb | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index d67ea1571dc..bd6fea8c286 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -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)