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).
Example:
So if you want to do this email operation only just the once (and then never again) then use
If you want to do it every time the object is saved, then do it in
The after_commit and after_rollback callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don’t interfere with the other callbacks. As such, if your callback code could raise an exception, you’ll need to rescue it and handle it appropriately within the callback.
For Example : Example of After commit
For more detail: rails transaction
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).
Example:
after_create
only works once - just after the record is first created.after_save
works every time you save the object - even if you're just updating it many years laterSo if you want to do this email operation only just the once (and then never again) then use
after_create
If you want to do it every time the object is saved, then do it in
after_save
The after_commit and after_rollback callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don’t interfere with the other callbacks. As such, if your callback code could raise an exception, you’ll need to rescue it and handle it appropriately within the callback.
For Example : Example of After commit
For more detail: rails transaction
1 comment:
u mean after_commit ??
Post a Comment