closure_tree icon indicating copy to clipboard operation
closure_tree copied to clipboard

dependent: :delete_all only deletes direct children

Open yijia-zhan opened this issue 9 years ago • 3 comments

class Tag
  has_closure_tree dependent: :delete_all
end

With the code above, @tag.destroy only deletes @tag's direct children. Its grandchildren are all orphaned, keeping old parent_ids which no longer exist. However, the hierarchy records of all direct children and grandchildren do get deleted though. Is this intended?

Thanks.

yijia-zhan avatar Dec 01 '16 21:12 yijia-zhan

Foreign keys shouldn't ever point to deleted records (and fk constraints should prevent that from happening). It should be a recursive delete.

Thanks for reporting this. PRs are welcome!

mceachen avatar Dec 01 '16 21:12 mceachen

Yeah, I'm surprised this can actually happen. Searched in the codebase a little bit, the :dependent option is simply only being passed into ActiveRecord, closure_tree doesn't seem to have any particular handling about destroying.

yijia-zhan avatar Dec 01 '16 21:12 yijia-zhan

If someone needs this and wants to take a swing at it, you'll need at least 3 steps:

  1. capture all descendant IDs (either in a temp table or in memory) via the hierarchy_ table
  2. DELETE all the references from the hierarchy_ table
  3. DELETE from the model table WHERE id IN (all descendant IDs)

mceachen avatar Mar 02 '17 16:03 mceachen