Search code examples
ruby-on-rails

Callbacks order in Rails


If I have code in my model file like this:

after_destroy :method_1
after_destroy :method_2

Do method_1 and method_2 execute together or method_1 first then method_2? Does it make a difference if I do:

after_destroy :method_1, method_2

A reference to the documentation would be great. thanks


Solution

  • ActiveRecord::Callbacks documents the order in "Ordering callbacks". The order changed subtly in Rails 7.1.

    Rails 7.1 and newer

    All callbacks are executed in the order they are defined.

    class Topic < ActiveRecord::Base
      after_save :log_children
      after_save :do_something_else
    
      ...
    end
    

    When a Topic is saved, log_children will be executed, then do_something_else.

    Prior to Rails 7.1

    Before Rails 7.1, transactional callbacks (after_commit, after_rollback) do the opposite; the last defined transactional callback is executed first.

    class Topic < ActiveRecord::Base
      after_commit :log_children
      after_commit :do_something_else
    
      ...
    end
    

    When a Topic is committed, first do_something_else runs, then log_children.

    If there's any doubt, you can combine them into a single callback.

    class Topic < ActiveRecord::Base
      after_commit :commit_callback
    
      private def commit_callback
        log_children
        do_something_else
      end
    
      ...
    end
    

    If you're upgrading Rails you can maintain compatibility by setting

    config.active_record.run_after_transaction_callbacks_in_order_defined = false
    

    See Active Record Callbacks - 11.3 Transactional Callback Ordering