Home > Articles > Web Development

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

9.3 Calculation Methods

All Active Record classes have a calculate method that provides easy access to aggregate function queries in the database. Methods for count, sum, average, minimum, and maximum have been added as convenient shortcuts.

Calculation methods can be used in combination with Active Record relation methods to customize the query. Since calculation methods do not return an ActiveRecord::Relation, they must be the last method in a scope chain.

There are two basic forms of output:

  • Single Aggregate Value The single value is typecast 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 :group option. It takes either a column name or the name of a belongs_to association.

The following examples illustrate the usage of various calculation methods.


 1 Person.calculate(:count, :all) # the same as Person.count
 2
 3 # SELECT AVG(age) FROM people
 4 Person.average(:age)
 5
 6 # Selects the minimum age for everyone with a last name other than "Drake."
 7 Person.where.not(last_name: 'Drake').minimum(:age)
 8
 9 # Selects the minimum age for any family without any minors.
10 Person.having('min(age) > 17').group(:last_name).minimum(:age)

9.3.1 average(column_name, *options)

Calculates the average value on a given column. The first parameter should be a symbol identifying the column to be averaged.

9.3.2 count(column_name, *options)

Count operates using three different approaches. Count without parameters will return a count of all the rows for the model. Count with a column_name will return a count of all the rows for the model with the supplied column present.

9.3.3 ids

Return all the ids for a relation based on its table’s primary key.

User.ids # SELECT id FROM "users"

9.3.4 maximum(column_name, *options)

Calculates the maximum value on a given column. The first parameter should be a symbol identifying the column to be calculated.

9.3.5 minimum(column_name, *options)

Calculates the minimum value on a given column. The first parameter should be a symbol identifying the column to be calculated.

9.3.6 pluck(*column_names)

The pluck method queries the database for one or more columns of the underlying table of a model.


>> User.pluck(:id, :name)
=> [[1, 'Obie']]
>> User.pluck(:name)
=> ['Obie']

It returns an array of values of the specified columns with the corresponding data type.

9.3.7 sum(column_name, *options)

Calculates a summed value in the database using SQL. The first parameter should be a symbol identifying the column to be summed.

  • + Share This
  • 🔖 Save To Your Account