How to safely use after_safe in Rails

Topics: Ruby on Rails

ActiveRecord in Ruby on Rails offers callbacks that get called at different stages of saving a record to the database. Using the after_save callback requires caution because it runs inside a transaction. This transaction might fail even after a specific after_save callback has already run, which means that the record will not get persisted after all.

For details, see How to Safely Use ActiveRecord’s after_save.

Only use after_save if the transaction context is actually required. Otherwise, prefer using after_commit. Since after_commit is also called after deleting a record, you can limit it to the “after save” case this way:

after_commit :your_method, if: :persisted?