After commit vs after save

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the rails category.

Last Updated: 2024-04-19

Rails runs after_save callbacks within a transaction, thus the state changes you just saved can theoretically be unwound if the transaction fails due to an exception getting raised within the after_save functionality. Sometimes this is what you want. Sometimes it isn't.

Whenever you are dealing with actions that should occur ONLY after you are sure everything is done (e.g. saving to a special full-text database, tracking, etc.), you ought to use after_commit since this gets run after and outside the transaction.

Note: In some systems after_commit will entail complications with testing state management systems which wrap data in a transaction and rollback at the test.