Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execution order of multiple after_commit callbacks (Rails)

I recently found that multiple after_commits defined in the same model get called in reverse order. For example

after_commit method1, :on => :create
after_commit method2, :on => :create

method2 gets called before method1.

Is it always called in FILO order?

like image 610
Sikai Zhu Avatar asked Jun 03 '15 16:06

Sikai Zhu


People also ask

What is the sequence of callbacks in Rails?

The callback order is as following:after_validation_on_create / after_validation_on_update. before_save. before_create.

How does callback work in Rails?

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

What is controller callback in Rails?

During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks (called callbacks) into this object life cycle so that you can control your application and its data. Callbacks allow you to trigger logic before or after an alteration of an object's state.

What is After_commit?

after_commit is a type of active record callback.


1 Answers

This behaviour is still present in Rails 5.2.2.1.

My solution:

after_commit :after_commit_callbacks, :on => :create

def after_commit_callbacks
  method1
  method2
end
like image 129
Railsana Avatar answered Oct 05 '22 11:10

Railsana