Skip to content

Commit

Permalink
Destroy in reverse order to rspect foreign keys (#478)
Browse files Browse the repository at this point in the history
Otherwise a foreign key error can occur if foreign keys have been added,
for example:

`Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails`
  • Loading branch information
kaspernj authored Oct 15, 2023
1 parent 285d35a commit 64006ba
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/awesome_nested_set/model/prunable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,14 @@ def destroy_descendants
end
end

# Use reverse to delete from deepest child to parent in order to respect any possible foreign keys
def decendants_to_destroy_in_order
descendants.reverse
end

def destroy_or_delete_descendants
if acts_as_nested_set_options[:dependent] == :destroy
descendants.each do |model|
decendants_to_destroy_in_order.each do |model|
model.skip_before_destroy = true
model.destroy
end
Expand Down
13 changes: 13 additions & 0 deletions spec/models/users_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,19 @@
expect(User.valid?).to be_truthy
end

it "destroys in the right order to respect foreign keys" do
User.acts_as_nested_set_options[:dependent] = :destroy

expect(users(:top_level).decendants_to_destroy_in_order).to eq [
users(:child_3),
users(:child_2_1),
users(:child_2),
users(:child_1)
]
expect(users(:top_level)).to receive(:decendants_to_destroy_in_order).once.and_call_original
expect { users(:top_level).destroy! }.to change(User, :count).by(-5)
end

it "assigning_parent_uuid_on_create" do
user = User.create!(:name => "Child", :parent_uuid => users(:child_2).uuid)
expect(users(:child_2)).to eq(user.parent)
Expand Down

0 comments on commit 64006ba

Please sign in to comment.