Files

Class Index [+]

Quicksearch

ActiveRecord::Calculations

Public Instance Methods

average(column_name, options = {}) click to toggle source

Calculates the average value on a given column. Returns nil if there’s no row. See calculate for examples with options.

  Person.average('age') # => 35.8
    # File lib/active_record/relation/calculations.rb, line 65
65:     def average(column_name, options = {})
66:       calculate(:average, column_name, options)
67:     end
calculate(operation, column_name, options = {}) click to toggle source

This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts. Options such as :conditions, :order, :group, :having, and :joins can be passed to customize the query.

There are two basic forms of output:

  * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
    for AVG, and the given column's type for everything else.
  * Grouped values: This returns an ordered hash of the values and groups them by the
    <tt>:group</tt> option.  It takes either a column name, or the name of a belongs_to association.

      values = Person.maximum(:age, :group => 'last_name')
      puts values["Drake"]
      => 43

      drake  = Family.find_by_last_name('Drake')
      values = Person.maximum(:age, :group => :family) # Person belongs_to :family
      puts values[drake]
      => 43

      values.each do |family, max_age|
      ...
      end

Options:

  • :conditions - An SQL fragment like “administrator = 1” or [ “user_name = ?”, username ]. See conditions in the intro to ActiveRecord::Base.

  • :include: Eager loading, see Associations for details. Since calculations don’t load anything, the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.

  • :joins - An SQL fragment for additional joins like “LEFT JOIN comments ON comments.post_id = id”. (Rarely needed). The records will be returned read-only since they will have attributes that do not correspond to the table’s columns.

  • :order - An SQL fragment like “created_at DESC, name” (really only used with GROUP BY calculations).

  • :group - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.

  • :select - By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join, but not include the joined columns.

  • :distinct - Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) …

Examples:

  Person.calculate(:count, :all) # The same as Person.count
  Person.average(:age) # SELECT AVG(age) FROM people...
  Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for
                                                                   # everyone with a last name other than 'Drake'

  # Selects the minimum age for any family without any minors
  Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name)

  Person.sum("2 * age")
     # File lib/active_record/relation/calculations.rb, line 145
145:     def calculate(operation, column_name, options = {})
146:       if options.except(:distinct).present?
147:         apply_finder_options(options.except(:distinct)).calculate(operation, column_name, :distinct => options[:distinct])
148:       else
149:         if eager_loading? || includes_values.present?
150:           construct_relation_for_association_calculations.calculate(operation, column_name, options)
151:         else
152:           perform_calculation(operation, column_name, options)
153:         end
154:       end
155:     rescue ThrowResult
156:       0
157:     end
count(column_name = nil, options = {}) click to toggle source

Count operates using three different approaches.

  • Count all: By not passing any parameters to count, it will return a count of all the rows for the model.

  • Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present.

  • Count using options will find the row count matched by the options used.

The third approach, count using options, accepts an option hash as the only parameter. The options are:

  • :conditions: An SQL fragment like “administrator = 1” or [ “user_name = ?”, username ]. See conditions in the intro to ActiveRecord::Base.

  • :joins: Either an SQL fragment for additional joins like “LEFT JOIN comments ON comments.post_id = id” (rarely needed) or named associations in the same form used for the :include option, which will perform an INNER JOIN on the associated table(s). If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table’s columns. Pass :readonly => false to override.

  • :include: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you’re counting. See eager loading under Associations.

  • :order: An SQL fragment like “created_at DESC, name” (really only used with GROUP BY calculations).

  • :group: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.

  • :select: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not include the joined columns.

  • :distinct: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) …

  • :from - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name of a database view).

Examples for counting all:

  Person.count         # returns the total count of all people

Examples for counting by column:

  Person.count(:age)  # returns the total count of all people whose age is present in database

Examples for count with options:

  Person.count(:conditions => "age > 26")

  # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
  Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job)

  # finds the number of rows matching the conditions and joins.
  Person.count(:conditions => "age > 26 AND job.salary > 60000",
               :joins => "LEFT JOIN jobs on jobs.person_id = person.id")

  Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
  Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')

Note: Person.count(:all) will not work because it will use :all as the condition. Use Person.count instead.

    # File lib/active_record/relation/calculations.rb, line 56
56:     def count(column_name = nil, options = {})
57:       column_name, options = nil, column_name if column_name.is_a?(Hash)
58:       calculate(:count, column_name, options)
59:     end
maximum(column_name, options = {}) click to toggle source

Calculates the maximum value on a given column. The value is returned with the same data type of the column, or nil if there’s no row. See calculate for examples with options.

  Person.maximum('age') # => 93
    # File lib/active_record/relation/calculations.rb, line 83
83:     def maximum(column_name, options = {})
84:       calculate(:maximum, column_name, options)
85:     end
minimum(column_name, options = {}) click to toggle source

Calculates the minimum value on a given column. The value is returned with the same data type of the column, or nil if there’s no row. See calculate for examples with options.

  Person.minimum('age') # => 7
    # File lib/active_record/relation/calculations.rb, line 74
74:     def minimum(column_name, options = {})
75:       calculate(:minimum, column_name, options)
76:     end
sum(column_name, options = {}) click to toggle source

Calculates the sum of values on a given column. The value is returned with the same data type of the column, 0 if there’s no row. See calculate for examples with options.

  Person.sum('age') # => 4562
    # File lib/active_record/relation/calculations.rb, line 92
92:     def sum(column_name, options = {})
93:       calculate(:sum, column_name, options)
94:     end

Private Instance Methods

aggregate_column(column_name) click to toggle source
     # File lib/active_record/relation/calculations.rb, line 186
186:     def aggregate_column(column_name)
187:       if @klass.column_names.include?(column_name.to_s)
188:         Arel::Attribute.new(@klass.unscoped.table, column_name)
189:       else
190:         Arel.sql(column_name == :all ? "*" : column_name.to_s)
191:       end
192:     end
column_alias_for(*keys) click to toggle source

Converts the given keys to the value that the database adapter returns as a usable column name:

  column_alias_for("users.id")                 # => "users_id"
  column_alias_for("sum(id)")                  # => "sum_id"
  column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
  column_alias_for("count(*)")                 # => "count_all"
  column_alias_for("count", "id")              # => "count_id"
     # File lib/active_record/relation/calculations.rb, line 255
255:     def column_alias_for(*keys)
256:       table_name = keys.join(' ')
257:       table_name.downcase!
258:       table_name.gsub!(/\*/, 'all')
259:       table_name.gsub!(/\W+/, ' ')
260:       table_name.strip!
261:       table_name.gsub!(/ +/, '_')
262: 
263:       @klass.connection.table_alias_for(table_name)
264:     end
column_for(field) click to toggle source
     # File lib/active_record/relation/calculations.rb, line 266
266:     def column_for(field)
267:       field_name = field.to_s.split('.').last
268:       @klass.columns.detect { |c| c.name.to_s == field_name }
269:     end
operation_over_aggregate_column(column, operation, distinct) click to toggle source
     # File lib/active_record/relation/calculations.rb, line 194
194:     def operation_over_aggregate_column(column, operation, distinct)
195:       operation == 'count' ? column.count(distinct) : column.send(operation)
196:     end
perform_calculation(operation, column_name, options = {}) click to toggle source
     # File lib/active_record/relation/calculations.rb, line 161
161:     def perform_calculation(operation, column_name, options = {})
162:       operation = operation.to_s.downcase
163: 
164:       distinct = nil
165: 
166:       if operation == "count"
167:         column_name ||= (select_for_count || :all)
168: 
169:         if arel.joins(arel) =~ /LEFT OUTER/
170:           distinct = true
171:           column_name = @klass.primary_key if column_name == :all
172:         end
173: 
174:         distinct = nil if column_name =~ /\s*DISTINCT\s+/
175:       end
176: 
177:       distinct = options[:distinct] || distinct
178: 
179:       if @group_values.any?
180:         execute_grouped_calculation(operation, column_name, distinct)
181:       else
182:         execute_simple_calculation(operation, column_name, distinct)
183:       end
184:     end
select_for_count() click to toggle source
     # File lib/active_record/relation/calculations.rb, line 288
288:     def select_for_count
289:       if @select_values.present?
290:         select = @select_values.join(", ")
291:         select if select !~ /(,|\*)/
292:       end
293:     end
type_cast_calculated_value(value, column, operation = nil) click to toggle source
     # File lib/active_record/relation/calculations.rb, line 271
271:     def type_cast_calculated_value(value, column, operation = nil)
272:       if value.is_a?(String) || value.nil?
273:         case operation
274:           when 'count'   then value.to_i
275:           when 'sum'     then type_cast_using_column(value || '0', column)
276:           when 'average' then value.try(:to_d)
277:           else type_cast_using_column(value, column)
278:         end
279:       else
280:         type_cast_using_column(value, column)
281:       end
282:     end
type_cast_using_column(value, column) click to toggle source
     # File lib/active_record/relation/calculations.rb, line 284
284:     def type_cast_using_column(value, column)
285:       column ? column.type_cast(value) : value
286:     end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.