What Does Rails Do With Both :dependent => :destroy and cascade delete/nullify/restrict What Does Rails Do With Both :dependent => :destroy and cascade delete/nullify/restrict ruby-on-rails ruby-on-rails

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.

  1. yes, you can use dependent: :destroy and on 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 like validates :some_field, uniqueness: true that is better to be backed by unique index, only database itself can ensure data consistency.

  2. since parent is deleted last, on delete nullify will not get in the way (you'll get nullified race condition records)

  3. there's transaction wrapping all deletes, only race condition records can be left over

  4. on delete restrict over dependent: :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.