Skip to content

Commit

Permalink
Merge pull request #2065 from mamhoff/quickly-destroy-nested-elements
Browse files Browse the repository at this point in the history
Delete nested elements quickly
  • Loading branch information
tvdeyen authored Apr 10, 2021
2 parents 8aaad84 + 2c0635d commit 55f1279
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
15 changes: 15 additions & 0 deletions app/models/alchemy/element.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ class Element < BaseRecord

has_many :contents, dependent: :destroy, inverse_of: :element

before_destroy :delete_all_nested_elements

has_many :all_nested_elements,
-> { order(:position) },
class_name: "Alchemy::Element",
Expand Down Expand Up @@ -347,5 +349,18 @@ def touch_touchable_pages

touchable_pages.each(&:touch)
end

def delete_all_nested_elements
deeply_nested_elements = descendent_elements(self).flatten
DeleteElements.new(deeply_nested_elements).call
nested_elements.reset
all_nested_elements.reset
end

def descendent_elements(element)
element.all_nested_elements + element.all_nested_elements.map do |nested_element|
descendent_elements(nested_element)
end
end
end
end
14 changes: 14 additions & 0 deletions spec/models/alchemy/element_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -968,4 +968,18 @@ module Alchemy
end
end
end

describe "destroy callbacks" do
let(:element) { create(:alchemy_element) }
let!(:nested_element_1) { create(:alchemy_element, parent_element: element) }
let!(:nested_element_2) { create(:alchemy_element, parent_element: nested_element_1) }
let!(:nested_element_3) { create(:alchemy_element, parent_element: nested_element_2) }

it "destroys all the nested elements quickly" do
expect(Alchemy::DeleteElements).to receive(:new).with(
[nested_element_1, nested_element_2, nested_element_3]
).and_call_original
element.reload.destroy!
end
end
end

0 comments on commit 55f1279

Please sign in to comment.