DEV Community 👩‍💻👨‍💻

Augusts Bautra
Augusts Bautra

Posted on

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).

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.