Using Before Destroy and Has Many in Rails

Using Before Destroy and Has Many in Rails

Aug 03, 2017 | By Matt |

Ruby on Rails, Development

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.

Written by Matt

Dad, husband, and Founder of Lotus Apps providing Rails and RubyMotion development out of Knoxville TN. Creator of http://www.gemprospector.com for #ruby devs.
Find me on:

Subscribe to Email Updates

Web vs Mobile software solutions
Pro
Why Should I Brand My Company?