after_save, after_create
and 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.save
on new objects that haven‘t been saved yet (no record exists) after_save Is called afterBase.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_save
and after_create
would 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_save
block.
Where as after_commit, is called after the execution of the final/outer transaction block. Thus the changes in the DB would be permanent.]]>
Hi hari really nice topic.
“So they [after_save, after_create] will be executed before executing the sql statement to make permanent changes in the DB.” https://stackoverflow.com/a/6249572/1611925 and other SO posts would disagree with that.