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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)