Subhash Chandra
Subhash Chandra

Reputation: 3265

Rails after_save and after_commit callbacks

I went through difference in after_save and after_commit callbacks in rails and major difference I found is after_commit calls both on create and update,is there a way to call after_commit only on create??

Upvotes: 1

Views: 5077

Answers (4)

DrewB
DrewB

Reputation: 3341

The other big difference is that after_save takes place in the same transaction as the create/save. This means that if there is an error the object is not created/saved. It also means that the row or table that the create/save is taking place on will be locked until the after_save completes. This can cause db performance issues or deadlocks. Particularly when you have several after_save call backs. In general, I default to using after_commit unless I have a good reason to do otherwise.

Upvotes: 0

after_create_commit :trigger

private
  def trigger
   # Your Code
  end

Upvotes: 1

tagCincy
tagCincy

Reputation: 1599

You are incorrect about the difference between the two callbacks. after_save is invoke when an object is created and updated, unless constrained as @Grammakov pointed out. after_commit fires on create, update and destroy.

The main difference is after_save invokes immediately after the model object save method completes, where after_commit doesn't fire until record is actually committed to the DB.

Upvotes: 2

The Whiz of Oz
The Whiz of Oz

Reputation: 7043

You can specify that the callback should only be fired by a certain action with the :on option:

after_commit :do_foo, on: :create
after_commit :do_bar, on: :update
after_commit :do_baz, on: :destroy

after_commit :do_foo_bar, on: [:create, :update]
after_commit :do_bar_baz, on: [:update, :destroy]

Upvotes: 5

Related Questions