/writing · 29 November 2026 · 6 min read

One guard to keep a Rails state machine honest

In a busy workflow app, records have a lifecycle: draft, active, closed, cancelled. Bugs rarely come from the happy path. They come from timing: a reminder scheduled last week fires after the job was cancelled, a half-finished update leaves a record stranded, and a "closed" job quietly reopens.

While fixing seven issues like these in SMATA's job lifecycle, I found the fix was rarely another if in another controller. It was moving the rule to one place, where nothing can get around it.

The problem with scattered checks

A typical codebase guards transitions where they happen: a check in the controller, another in a service object, a third in a background job. Every new entry point (an API endpoint, a webhook, a rake task) has to remember the rule. Eventually one doesn't.

One guard on the model

Put the rule where every write passes through. With Rails' dirty tracking you can see both the old and new status without an extra query:

class Job < ApplicationRecord
  TERMINAL = %w[cancelled closed].freeze

  validate :terminal_states_are_final, on: :update

  private

  def terminal_states_are_final
    return unless will_save_change_to_status?
    from = status_in_database
    errors.add(:status, "can't change once #{from}") if TERMINAL.include?(from)
  end
end

Now a controller, an API, a webhook and a console session all hit the same wall. If you use a state-machine gem, the same idea applies: one guard that covers every event, rather than a condition on each one.

Scheduled work must re-check state

A job enqueued while a record was active can run after it's cancelled. Check the state when the job runs, not when it was scheduled:

class SendReminderJob < ApplicationJob
  def perform(job_id)
    job = Job.find_by(id: job_id)
    return if job.nil? || Job::TERMINAL.include?(job.status)

    JobMailer.reminder(job).deliver_now
  end
end

All or nothing for multi-step changes

When one action changes several things, such as assigning a contractor and scheduling notifications, a failure halfway leaves a record nobody can explain. Wrap the steps in a transaction, and send emails only after the commit so a rollback can't send them.

Job.transaction do
  job.assign_contractor!(contractor)
  job.schedule_notifications!
end

Specs for the failure paths

Happy-path tests won't catch these bugs. Test what happens when things go wrong:

it "leaves nothing behind when scheduling fails" do
  allow(job).to receive(:schedule_notifications!).and_raise(StandardError, "boom")

  expect { AssignContractor.new(job, contractor).call }.to raise_error(StandardError)
  expect(job.reload.contractor).to be_nil
end

it "refuses to reopen a cancelled job" do
  job = create(:job, status: "cancelled")
  expect(job.update(status: "active")).to be(false)
end

The checklist

  • One guard on the model, not checks in every caller.
  • Dirty tracking, so the guard needs no extra query for the old value.
  • Background jobs re-check state when they run.
  • Multi-step changes in a transaction; emails after commit.
  • Specs that force failures and try forbidden transitions.

/more-writing

Start a project