What Does Rails Do With Both :dependent => :destroy and cascade delete/nullify/restrict
With dependent: :destroy
in a transaction rails first destroys all dependencies, and only then deletes the record itself.
There may be a race condition: if a dependent record was added just after rails read collection for destroying, but not deleted parent yet - it may be left over. Let's call these "race condition records" below.
yes, you can use
dependent: :destroy
andon delete cascade
, this way some children (race condition ones) can be deleted without callbacks. If callbacks are mandatory -on delete restrict
together with some locking and explicit children deletion may be better.This is somewhat likevalidates :some_field, uniqueness: true
that is better to be backed by unique index, only database itself can ensure data consistency.since parent is deleted last,
on delete nullify
will not get in the way (you'll get nullified race condition records)there's transaction wrapping all deletes, only race condition records can be left over
on delete restrict
overdependent: :destroy
will trigger only for race condition records (and roll back whole transaction), but if there was no race condition - rails will happily delete everything.