Preventing Invalid Enum Transitions with Callbacks

Using before_update, you can restrict enum changes to ensure logical transitions.

Example: Preventing Order Status Reversal

class Order < ApplicationRecord
  enum :status, { pending: 0, confirmed: 1, shipped: 2, delivered: 3, canceled: 4 }

  before_update :prevent_invalid_status_change

  private

  def prevent_invalid_status_change
    if status_was == "delivered" && status != "delivered"
      errors.add(:status, "cannot be changed after delivery")
      throw(:abort)
    end
  end
end

Now, if an order is delivered, its status cannot be changed back to a previous state.