after_commit are called active record call backs in rails. They get executed when we work on the database, similarly we also have before_* callback and callbacks on destroy as well. In this article I will explain you about the difference between *_save, *_create and *_commit callbacks.
The purpose of each as per rails docs:
after_create Is called afterNow to explain the real difference between the three, we must first explain about database transaction. They are a protective block around a group of sql statements, that are permanent only if all of them succeed in a single atomic statement.
Base.saveon new objects that haven‘t been saved yet (no record exists) after_save Is called after
Base.save(regardless of whether it‘s a create or update save) after_commit Is called after the database transaction is completed.
User.transaction do # update company # update hr_department # update user_table endWhen rails execute a create, the
after_createwould be called within the transaction block of the create statement. So they will be executed before executing the sql statement to make permanent changes in the DB. If the query fails, then no change will happen to the DB, but we would have executed the instructions of the after_create and
after_saveblock. Where as after_commit, is called after the execution of the final/outer transaction block. Thus the changes in the DB would be permanent.]]>