[ activeRecord ] callbacks steps

(-) save

(-) valid

(1) before_validation

(-) validate

(2) after_validation

(3) before_save

(4) before_create

(-) create

(5) after_create

(6) after_save

(7) after_commit

after_create v.s. after_save v.s. after_commit

​​​after_create : 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). Originally posted here

That also means, that if after_commit raises an exception, then the transaction won’t be rolled back ****.

 

after_create :

Is called after Base.save on 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.

 

ref : https://stackoverflow.com/questions/22952664/what-is-the-difference-between-before-create-and-after-create-and-when-to-us ,

https://stackoverflow.com/questions/33890458/difference-between-after-create-after-save-and-after-commit-in-rails-callbacks ,

https://stackoverflow.com/questions/15746362/after-create-foo-vs-after-commit-bar-on-create/15753859#15753859 ,

https://blog.redpanthers.co/after_create-vs-after_save-vs-after_commit/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s