From 023accf6a8fb00fc7a772b736e2f790b29a3ea66 Mon Sep 17 00:00:00 2001 From: Krzysztof Kotlarek Date: Fri, 20 Jan 2023 13:29:49 +1100 Subject: [PATCH] FIX: deleted misconfigured embeddable hosts (#19833) When EmbeddableHost is configured for a specific category and that category is deleted, then EmbeddableHost should be deleted as well. In addition, migration was added to fix existing data. --- app/models/category.rb | 1 + ...3_delete_misconfigured_embeddable_hosts.rb | 19 +++++++++++++++++++ spec/models/category_spec.rb | 6 ++++++ 3 files changed, 26 insertions(+) create mode 100644 db/migrate/20230111223803_delete_misconfigured_embeddable_hosts.rb diff --git a/app/models/category.rb b/app/models/category.rb index fc721f09405..220ca006cd7 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -130,6 +130,7 @@ class Category < ActiveRecord::Base has_many :category_required_tag_groups, -> { order(order: :asc) }, dependent: :destroy has_many :sidebar_section_links, as: :linkable, dependent: :delete_all + has_many :embeddable_hosts, dependent: :destroy belongs_to :reviewable_by_group, class_name: "Group" diff --git a/db/migrate/20230111223803_delete_misconfigured_embeddable_hosts.rb b/db/migrate/20230111223803_delete_misconfigured_embeddable_hosts.rb new file mode 100644 index 00000000000..89c54d10520 --- /dev/null +++ b/db/migrate/20230111223803_delete_misconfigured_embeddable_hosts.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +class DeleteMisconfiguredEmbeddableHosts < ActiveRecord::Migration[7.0] + def up + execute(<<~SQL) + DELETE FROM embeddable_hosts eh1 + WHERE eh1.id IN ( + SELECT eh2.id FROM embeddable_hosts eh2 + LEFT JOIN categories ON categories.id = eh2.category_id + WHERE eh2.category_id IS NOT NULL + AND categories.id IS NULL + ) + SQL + end + + def down + raise ActiveRecord::IrreversibleMigration + end +end diff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rb index ecabfc50c68..da44f31eb4f 100644 --- a/spec/models/category_spec.rb +++ b/spec/models/category_spec.rb @@ -577,6 +577,12 @@ RSpec.describe Category do expect(SiteSetting.shared_drafts_category).to be_blank end + it "deletes related embeddable host" do + embeddable_host = Fabricate(:embeddable_host, category: @category) + @category.destroy! + expect { embeddable_host.reload }.to raise_error(ActiveRecord::RecordNotFound) + end + it "triggers a extensibility event" do event = DiscourseEvent.track(:category_destroyed) { @category.destroy }