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

Ruby on-Rails

Ruby on-Rails Problem Overview


Is there any difference between:

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

Can these be used interchangeably?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

Solution 2 - Ruby on-Rails

There is one major difference between these two with respect to associations. after_create is called as soon as an insert query is fired for the given object, and before the insert queries of the associations of the object. This means the values of the associated objects can be changed directly in after_create callbacks without update query.

class Post < ActiveRecord::Base
  has_one :post_body
  after_create :change_post_body

  def change_post_body
    self.post_body.content = "haha"
    #No need to save
  end 
end

Solution 3 - Ruby on-Rails

Rails 5

You can use after_create_commit :method_name to only call this callback on create.

Warning

Using both after_create_commit and after_update_commit in the same model will only allow the last callback defined to take effect, and will override all others.

Source: https://guides.rubyonrails.org/active_record_callbacks.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBillView Question on Stackoverflow
Solution 1 - Ruby on-RailsFrederick CheungView Answer on Stackoverflow
Solution 2 - Ruby on-Railsuser3161928View Answer on Stackoverflow
Solution 3 - Ruby on-RailsGuillaumeView Answer on Stackoverflow