0
0
RailsHow-ToBeginner · 3 min read

How to Use Maximum and Minimum in Ruby on Rails Models

In Ruby on Rails, use Model.maximum(:column_name) to get the highest value and Model.minimum(:column_name) to get the lowest value from a database column. These methods return the maximum or minimum value directly from the database efficiently.
📐

Syntax

The maximum and minimum methods are called on an ActiveRecord model to find the highest or lowest value of a specific column.

  • Model.maximum(:column_name) returns the largest value in the specified column.
  • Model.minimum(:column_name) returns the smallest value in the specified column.

Replace Model with your model name and :column_name with the column you want to check.

ruby
Model.maximum(:column_name)
Model.minimum(:column_name)
💻

Example

This example shows how to find the highest and lowest prices from a Product model with a price column.

ruby
class Product < ApplicationRecord
end

# Find the highest price
max_price = Product.maximum(:price)

# Find the lowest price
min_price = Product.minimum(:price)

puts "Highest price: #{max_price}"
puts "Lowest price: #{min_price}"
Output
Highest price: 150 Lowest price: 10
⚠️

Common Pitfalls

Common mistakes include:

  • Calling maximum or minimum on a non-existent column causes an error.
  • Expecting these methods to return records instead of values; they return only the value of the column.
  • Using them on empty tables returns nil, so always check for nil before using the result.
ruby
wrong = Product.maximum(:nonexistent_column) # Raises error

# Correct usage:
max_price = Product.maximum(:price)
if max_price.nil?
  puts "No products found"
else
  puts "Max price is #{max_price}"
end
📊

Quick Reference

MethodDescriptionReturns
maximum(:column_name)Returns the highest value in the columnValue or nil if no records
minimum(:column_name)Returns the lowest value in the columnValue or nil if no records

Key Takeaways

Use Model.maximum(:column_name) to get the highest value in a column.
Use Model.minimum(:column_name) to get the lowest value in a column.
These methods return the value directly, not the full record.
Check for nil results when the table is empty to avoid errors.
Ensure the column name exists to prevent runtime exceptions.