Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

after_create :foo vs after_commit :bar, :on => :create

Is there any difference between:

after_create :after_create and after_commit :after_commit_on_create, :on => :create

Can these be used interchangeably?

like image 639
Bill Avatar asked Apr 01 '13 15:04

Bill


People also ask

What is the difference between After_save and after_commit?

The difference between after_create , after_save and after_commit in Rails is that: after_save is invoked when an object is created and updated. after_commit is called on create, update and destroy. after_create is only called when creating an object.

What does after_commit do in Rails?

When a transaction completes, the after_commit or after_rollback callbacks are called for all models created, updated, or destroyed within that transaction.

When to use after_ commit?

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.

What is after_ commit?

after_commit is a type of active record callback.


1 Answers

They are not interchangeable. The key difference is when the callback runs. In the case of after_create, this will always be before the call to save (or create) returns.

Rails wraps every save inside a transaction and the before/after create callbacks run inside that transaction (a consequence of this is that if an exception is raised in an after_create the save will be rolled back). With after_commit, your code doesn't run until after the outermost transaction was committed. This could be the transaction rails created or one created by you (for example if you wanted to make several changes inside a single transaction).

At the point when after_save/create runs, your save could still be rolled back and (by default) won't be visible to other database connections (e.g. a background task such as sidekiq). Some combination of these 2 is usually the motivation for using after_commit.

like image 132
Frederick Cheung Avatar answered Oct 03 '22 00:10

Frederick Cheung