Learn Rails Callbacks in 30 seconds
Callbacks Useful or Dangerous?
Rails callbacks automate real work. Used carelessly, one line of code fires
four things you forgot about.
THE PROBLEM
Callbacks run automatically at points in an Active Record object's lifecycle.
A single `user.save` can normalize data, send email, sync a CRM and reindex
search — none of it visible at the call site. That's not a bug, it's the
design. It becomes a problem when business logic hides inside it and your
tests have to fight the model to do anything.
THE CLASSIC BUG
after_create do
WelcomeJob.perform_later(self)
end
Looks fine. Fails intermittently in production.
`after_create` fires inside the transaction, before COMMIT. Enqueue a job
there and your worker can pick it up before the row is visible to other
connections — so it blows up with RecordNotFound. It passes locally because
your test runs fast or wraps everything in a transaction. It fails under
load, which is the worst time to find out.
THE FIX
after_commit on: :create do
WelcomeJob.perform_later(self)
end
`after_commit` runs once the transaction has actually committed. The row is
there. The job finds it.
THE ACTUAL RULE
Callbacks are fine for small, in-memory, lifecycle-shaped work —
`before_validation :normalize_email` is exactly what they're for. The line
isn't "callbacks bad." It's:
• Keep callbacks small
• Make side effects explicit
• Anything external — email, HTTP, jobs — goes in `after_commit`
And moving work to a background job doesn't make it reliable by itself.
Jobs still need retries, idempotency, and a plan for the dead letter queue.
`deliver_later` is not a delivery guarantee.
—
#Astmation — #software #systems, #automation, and #AI-powered #applications .
Build. Automate. Evolve.
https://astmation.com/
#Shorts #RubyOnRails #Rails #ActiveRecord #Sidekiq #BackendDevelopment #RubyProgramming #SoftwareEngineering #CleanCode #WebDevelopment
Watch on YouTube