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

狂风中的少年 提交于 2019-12-04 00:22:22

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!