How to Use sum in Rails: Simple Guide with Examples
In Rails, you can use the
sum method on ActiveRecord relations to add up values of a specific column. For example, Model.sum(:column_name) returns the total of that column for all records matching the query.Syntax
The sum method is called on an ActiveRecord relation or model and takes a column name as a symbol or string. It returns the total sum of that column's values.
Model.sum(:column_name)- sums the values ofcolumn_namefor all records.Model.where(condition).sum(:column_name)- sums values filtered by a condition.
ruby
Model.sum(:column_name)
Model.where(active: true).sum(:price)Example
This example shows how to sum the prices of all products and then sum prices only for active products.
ruby
class Product < ApplicationRecord # Assume products table has columns: name:string, price:decimal, active:boolean end # Sum of all product prices all_prices_sum = Product.sum(:price) # Sum of prices for active products only active_prices_sum = Product.where(active: true).sum(:price) puts "Total price of all products: #{all_prices_sum}" puts "Total price of active products: #{active_prices_sum}"
Output
Total price of all products: 1500.75
Total price of active products: 1200.50
Common Pitfalls
Common mistakes include:
- Passing a block to
suminstead of a column name, which does not work on ActiveRecord relations. - Using
sumon non-numeric columns, which will cause errors. - Forgetting to filter records before summing, leading to sums of all records unintentionally.
ruby
# Wrong: passing block to sum on ActiveRecord
Product.sum { |p| p.price } # This sums in Ruby, not in database, and loads all records
# Right: use sum with column name for database calculation
Product.sum(:price)
# Wrong: summing a non-numeric column
Product.sum(:name) # Error or unexpected result
# Right: sum only numeric columns
Product.sum(:price)Quick Reference
Tips for using sum in Rails:
- Use
sum(:column)to calculate totals efficiently in the database. - Combine with
whereto sum filtered records. - Ensure the column is numeric (integer, decimal, float).
- Do not pass blocks to
sumon ActiveRecord relations.
Key Takeaways
Use
sum(:column_name) on ActiveRecord models to get the total of a numeric column.Combine
sum with where to sum only filtered records.Do not pass blocks to
sum on ActiveRecord relations; it expects a column name.Ensure the column you sum is numeric to avoid errors.
Using
sum performs the calculation in the database for better performance.