From 35e0a3c3c2749435cf7001d7f3451a43ec650d9c Mon Sep 17 00:00:00 2001 From: Martin Meyerhoff Date: Wed, 10 Apr 2024 20:58:04 +0200 Subject: [PATCH] Nullify referencing EssencePages on page deletion It's impossible to delete a page if it is referenced from an EssencePage. Currently, we get a ForeignKeyConstraint error if we intend to do this; but it would be much nicer if the essence would stay where it is and stop referencing the page. --- app/models/alchemy/page.rb | 2 ++ spec/models/alchemy/page_spec.rb | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/app/models/alchemy/page.rb b/app/models/alchemy/page.rb index 47a4e8cbfb..ca602d0297 100644 --- a/app/models/alchemy/page.rb +++ b/app/models/alchemy/page.rb @@ -121,6 +121,8 @@ class Page < BaseRecord has_one :draft_version, -> { drafts }, class_name: "Alchemy::PageVersion" has_one :public_version, -> { published }, class_name: "Alchemy::PageVersion", autosave: -> { persisted? } + has_many :page_essences, class_name: "Alchemy::EssencePage", foreign_key: :page_id, inverse_of: :ingredient_association, dependent: :nullify + before_validation :set_language, if: -> { language.nil? } diff --git a/spec/models/alchemy/page_spec.rb b/spec/models/alchemy/page_spec.rb index 3332c1c7fb..20ba456ac8 100644 --- a/spec/models/alchemy/page_spec.rb +++ b/spec/models/alchemy/page_spec.rb @@ -220,6 +220,14 @@ module Alchemy it "destroys elements along with itself" do expect { page.destroy! }.to change(Alchemy::Element, :count).from(3).to(0) end + + context "with an essence page pointing to the page" do + let!(:essence_page) { create(:alchemy_essence_page, page: page) } + + it "nullifies the essence on destruction" do + expect { page.destroy! }.to change { essence_page.reload.page_id }.from(page.id).to(nil) + end + end end end