[Talking-Rails] ActiveRecord::Calculations speed up Rails app by calculating aggregate values of columns in ActiveRecord models
ActiveRecord::Calculations speed up Rails app
In general scenarios, calculations that can be done at the database level are not recommended to be done at the Rails app level if there are no special requirements. Avoid unnecessary time, network and resource consumption
ActiveRecord::Calculations
provide methods for calculating aggregate values of columns in ActiveRecord
models.
Instance Public methods
average(column_name)
Calculates the average value on a given column. Returns nil
if there’s no row. See calculate for examples with options.
1 | Person.average(:age) # => 35.8 |
calculate(operation, column_name)
This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
1 | Person.calculate(:count, :all) # The same as Person.count |
There are two basic forms of output:
-
Single aggregate value: The single value is type cast to
Integer
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. It takes either a column name, or the name of a belongs_to association.
1 | values = Person.group('last_name').maximum(:age) |
count(column_name = nil)
Count the records.
1 | Person.count |
If count is used with Relation#group
, it returns a Hash whose keys represent the aggregated column, and the values are the respective amounts:
1 | Person.group(:city).count |
If count is used with Relation#group
for multiple columns, it returns a Hash whose keys are an array containing the individual values of each column and the value of each key would be the count.
1 | Article.group(:status, :category).count |
If count is used with Relation#select
, it will count the selected columns:
1 | Person.select(:age).count |
Note: not all valid Relation#select
expressions are valid count expressions. The specifics differ between databases. In invalid cases, an error from the database is thrown.
ids()
Pluck all the ID’s for the relation using the table’s primary key
1 | Person.ids # SELECT people.id FROM people |
maximum(column_name)
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.
1 | Person.maximum(:age) # => 93 |
pick(*column_names)Link
Pick the value(s) from the named column(s) in the current relation. This is short-hand for `relation.limit(1).pluck(*column_names).first1, and is primarily useful when you have a relation that’s already narrowed down to a single row.
Just like pluck, pick will only load the actual value, not the entire record object, so it’s also more efficient. The value is, again like with pluck, typecast by the column type.
1 | Person.where(id: 1).pick(:name) |
pluck(*column_names)
Use pluck
as a shortcut to select one or more attributes without loading a bunch of records just to grab the attributes you want.
1 | Person.pluck(:name) |
instead of
1 | Person.all.map(&:name) |
Pluck returns an Array
of attribute values type-casted to match the plucked column names, if they can be deduced. Plucking an SQL fragment returns String values by default.
1 | Person.pluck(:name) |
See also ids - https://api.rubyonrails.org/v6.1.4/classes/ActiveRecord/Calculations.html#method-i-ids.
sum(column_name = nil)
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.
1 | Person.sum(:age) # => 4562 |
Performance tips
Optimize the performance of a Ruby on Rails app by calculating aggregate values of columns.
Prefer pluck instead of map
If you are interested in only a few values per row, you should use pluck instead of map.
For example:
1 | Order.where(number: 'R545612547').map &:id |
As with select, map will load the order into memory and it will get the id attribute.
Using pluck will be faster, because it doesn’t need to load an entire object into memory.
So this will be much faster:
1 | Order.where(number: 'R545612547').pluck :id |
For this particular case, pluck is six times faster than map.
Prefer ActiveRecord::Calculations#sum instead of Enumerable#sum
Usually in Rails applications we find many references to Enumerable::sum for summing values. This is a common mistake because ActiveRecord::Calculations provides a way to do this without loading a bunch of ActiveRecord objects in memory. If you want to perform mathematical operations for a set of records following the Rails way, ActiveRecord::Calculations is the best way to do them in the database.
1 | Benchmark.ips do |x| |
Prefer ActiveRecord::Calculations#maximum instead of Enumerable#max
As we explained above, to perform better with calculations you should use ActiveRecord::Calculations methods whenever is possible.
1 | Benchmark.ips do |x| |
Prefer ActiveRecord::Calculations#minimum instead of Enumerable#min
1 | Benchmark.ips do |x| |