Understanding State Machines and Enums
A state machine defines how an object transitions between different states based on events or conditions.
Rails enums provide a way to store and query states efficiently, but they lack transition rules that prevent invalid state changes.
For example, with a basic enum:
class Order < ApplicationRecord
enum :status, { pending: 0, confirmed: 1, shipped: 2, delivered: 3, canceled: 4 }
end
The issue is any status can be set directly, even if the transition doesn’t make sense:
order = Order.new
order.status = :shipped # Invalid if not confirmed first
order.save!
Why Use a State Machine Instead of Just Enums?
Feature | Enum ✅ | State Machine ✅ |
---|---|---|
Simple statuses | ✅ Yes | ✅ Yes |
Enforce transition rules | ❌ No | ✅ Yes |
Callbacks for transitions | ❌ No | ✅ Yes |
Preventing invalid changes | ❌ No | ✅ Yes |
If your status transitions have rules, using a state machine is better.