Difference between after_create, after_save and after_commit in rails callbacks

The difference between after_create , after_save and after_commit in Rails is that:

  • after_save is called when creating and updating an object
  • after_commit is called upon creation, update, and destruction.
  • after_create is called only when an object is created

Is this the only difference between them or are there other significant differences?

+36
ruby callback ruby-on-rails activerecord
source share
2 answers

You almost understood everything. However, there is one significant difference between after_commit and after_create or after_save i.e.

In the case of after_create this will always be before calling the save (or create) return.

Rails wraps each saved transaction, and before / after callbacks are triggered in this transaction (this is due to the fact that if an exception is raised in post_create, the saving will be canceled). With after_commit your code does not run until the most external transaction has been completed. These can be created transaction rails or created by you (for example, if you want to make several changes within one transaction). Originally posted here

It also means that if after_commit throws an exception, the transaction will not be after_commit .

+48
source share

With callback order

after_create -

Called after Model.save for new objects that have not yet been saved (the record does not exist)

after_save -

Called after Model.save (regardless of whether it is created or updated or saved)

after_commit -

Called upon completion of a database transaction.

+6
source share

All Articles