📎 Webclip
A Couple of Callback Gotchas (and a Rails 5 Fix)
Rails callbacks can run code during different stages of a model’s lifecycle, but using after_save to enqueue background work can race with the database transaction. A job may try to load a record before the commit finishes, so another process cannot find it yet.
Reading notes#
after_saveruns before the surrounding transaction is committed, so Sidekiq may not be able to see the saved record yet.- The example switches the indexing hook from
after_savetoafter_commitso the job is queued only after the record becomes visible to other database connections. - Rails test cases wrap each test in a transaction, which prevents
after_commitfrom running in the usual way. - The
test_after_commitgem makes those callbacks run in tests after the relevant transaction boundary. - The post says Rails 5 fixed this testing problem, so the extra gem would no longer be needed there.
