DEV Community

Augusts Bautra
Augusts Bautra

Posted on

1 1

Always `prepend: true` for `before_destroy` callbacks

Today I encountered a gotcha where a spec for a before_destroy callback started to fail after I moved the callback definition to after associations, as is good form.

Turns out, association dependent: :destroy options define before_destroy callbacks themselves and since callbacks are normally executed in order of definition, they started to take precedence over the callback that was failing.

The fix for this problem is easy, add a prepend: true option to the callback. In fact, it's probably a good, future-proof practice to always define before_destroy :my_callback, prepend: true.

See also a Rails thread on this topic, and an SO thread (where I've weighed in).

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More