0
0
RailsHow-ToBeginner · 3 min read

How to Use Average in Rails: ActiveRecord Average Method Guide

In Rails, you can calculate the average of a column using ActiveRecord's average method, like Model.average(:column_name). This returns the average value as a decimal or nil if no records exist.
📐

Syntax

The average method is called on an ActiveRecord model or relation and takes the column name as a symbol or string. It calculates the average value of that column for all matching records.

  • Model.average(:column_name): Returns the average of the specified column.
  • The result is a BigDecimal or nil if no records exist.
ruby
Model.average(:column_name)
💻

Example

This example shows how to calculate the average price of products in a Rails app using ActiveRecord.

ruby
class Product < ApplicationRecord
end

# Assuming products table has a 'price' column
average_price = Product.average(:price)
puts "Average price: #{average_price}"
Output
Average price: 25.75
⚠️

Common Pitfalls

Common mistakes when using average include:

  • Calling average on an empty table returns nil, so always check for nil before using the result.
  • Passing a column name that does not exist will raise an error.
  • Using average on a non-numeric column will cause unexpected results or errors.
ruby
wrong = Product.average(:nonexistent_column) # Raises error

correct = Product.average(:price) || 0 # Returns 0 if no records
📊

Quick Reference

  • Model.average(:column): Calculate average of a numeric column.
  • Returns BigDecimal or nil if no records.
  • Use || 0 or conditional checks to handle nil.
  • Works with scopes and relations, e.g. Model.where(condition).average(:column).

Key Takeaways

Use ActiveRecord's average method with a column symbol to get the average value.
The average method returns nil if no records match, so handle nil safely.
Only use average on numeric columns to avoid errors.
You can chain average with scopes to calculate averages on filtered data.
Always verify the column name exists to prevent runtime errors.