- 9.1 Scopes
- 9.2 Callbacks
- 9.3 Calculation Methods
- 9.4 Single-Table Inheritance (STI)
- 9.5 Abstract Base Model Classes
- 9.6 Polymorphic has_many Relationships
- 9.7 Enums
- 9.8 Foreign-Key Constraints
- 9.9 Modules for Reusing Common Behavior
- 9.10 Modifying Active Record Classes at Runtime
- 9.11 Using Value Objects
- 9.12 Nonpersisted Models
- 9.13 PostgreSQL Enhancements
- 9.14 Conclusion
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.
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.
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.