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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay