Using Before Destroy and Has Many in Rails

A quick tip for utilizing a before_destroy callback in Rails alongside associations.

The Problem

It's not often we make use of "before_destroy" callbacks in Rails (in fact, we advocate for service objects); however, we found ourselves wanting to make use of this callback recently to process data in a has many relationship.

Archive Association on Destroy

In the following example, we want to perform some logic on any associated models using an ActiveJob worker, as well as ensure that each payment method is updated to remove the reference to this parent model.

With this code however, when our callback is executed, payment_methods will be empty, as the dependent: :nullify has already set the foreign key value to null for each.

Prepend the Callback

As it turns out, the dependent option on a has_many association is implemented as a callback itself, a before_destroy to be exact. So while we could write a custom before_action that also handles the nullification of the foreign key, we couldn't easily reuse this existing service.

In this scenario, we simply prepend our callback so it is executed before foreign key nullification occurs.

Ready to have a chat?

Contact us to chat with our founder
so we can learn about you and your project.