changing the after_commit callback execution order for related classes

Viewed 96

I have two classes A & B. B is having belongs_to relationship with A:

B {
     relationships:{
        A  {type: :belongs_to}
     }
}

I'm using active record after_commit callbacks in the models of both A & B, something like below:

A {
     after_commit -> { commit_to_kafka_for_a }, :on => :create
}

B {
     relationships:{
        A  {type: :belongs_to}
     }
     after_commit -> { commit_to_kafka_for_b }, :on => :create
}

When I run both of these in a Transaction:

ActiveRecord::Base.transaction do

  a_obj = A.new
  B.a_obj = a_obj
  B.save!

end

In the transaction steps, A is the first object that is created. The after_commit of B (which is a child entity) is called first. , i.e sequence of callbacks execution:

 1. commit_to_kafka_for_b
 2. commit_to_kafka_for_a

Is there any way I can call the after_commit of parent class A first, then the child class (B). A sequence like:

 1. commit_to_kafka_for_a
 2. commit_to_kafka_for_b

Can someone help on this?

0 Answers
Related