Caution when using before_destroy with model association

The other day, I was tasked with calling an external service when destroying a user. This kind of task is pretty straightforward in Rails, you call a method in a before_destroy callback on your model.

This led me to a very instructive discovery about ActiveRecord callbacks and model dependencies.

First of all, here’s the very simplified schema of what we are working on:

As I was dealing with an external service, I wanted to process that task in a Sidekiq job. That job needed the user’s authorization uuid to complete its task.

So, part of my Rspec test was to expect the Sidekiq job to receive the user’s authorization uuid as parameter. But strangely enough, it was always failing.

I ran a tail -f tmp/test.log to dig into execution logs:

As you can see the code tries to read the user’sauthorization uuid after it was deleted.

Because on the top of the model you have :
has_many :authorizations, dependent: :delete_all

In fact when there is dependent: delete_all or dependent: destroy.

They are implemented like before_destroy callback, and since callbacks are executed in the order they’re defined, the :dependent callback is run before the :check callback. The solution seems to be either force the :dependent callback to run last, or make it its own callback.

So at first I just inverted the order of before_destroy and has_many (following “Ordering callbacks” guide)

It works, but you can do it differently. Use prepend: true (see : ActiveSupport::Callbacks::ClassMethods#method-i-set_callback)

This is for us the cleaner way and this is what we chose.

What does prepend do?

prepend can be used for callbacks in general. It’s part of ActiveSupport.

:prepend — If true, the callback will be prepended to the existing chain rather than appended.

In our case, with the usermodel we can see the callback order using _destroy_callbacks method :

lambda in the callback chains are the dependent: :delete_all or dependent: :destroy before_destroy actions.


You should subscribe to our blog to be notified whenever a new article is available!

This article was written by part of Appaloosa’s dev team: 
Benoit Tigeot

Want to be part of Appaloosa? Head to Welcome to the jungle.