From a8b2e7e343d9b56564bf7a9189d15006dee24a8c Mon Sep 17 00:00:00 2001
From: Vinoth Kannan <svkn.87@gmail.com>
Date: Mon, 20 Sep 2021 11:20:49 +0530
Subject: [PATCH] DEV: trash category definition topic instead of destroying.
 (#14356)

After deleting a category, we should soft-delete the category definition topic instead of hard deleting it. Else it causes issues while doing the user merge action if the source user has an orphan post that belongs to the deleted topic.
---
 app/models/category.rb       | 7 ++++++-
 spec/models/category_spec.rb | 2 +-
 2 files changed, 7 insertions(+), 2 deletions(-)

diff --git a/app/models/category.rb b/app/models/category.rb
index d36d490ace9..07b890e0644 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -25,7 +25,7 @@ class Category < ActiveRecord::Base
   register_custom_field_type(REQUIRE_REPLY_APPROVAL, :boolean)
   register_custom_field_type(NUM_AUTO_BUMP_DAILY, :integer)
 
-  belongs_to :topic, dependent: :destroy
+  belongs_to :topic
   belongs_to :topic_only_relative_url,
               -> { select "id, title, slug" },
               class_name: "Topic",
@@ -67,6 +67,7 @@ class Category < ActiveRecord::Base
   validates :slug, exclusion: { in: RESERVED_SLUGS }
 
   after_create :create_category_definition
+  after_destroy :trash_category_definition
 
   before_save :apply_permissions
   before_save :downcase_email
@@ -296,6 +297,10 @@ class Category < ActiveRecord::Base
     end
   end
 
+  def trash_category_definition
+    self.topic&.trash!
+  end
+
   def topic_url
     if has_attribute?("topic_slug")
       Topic.relative_url(topic_id, read_attribute(:topic_slug))
diff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rb
index 63c38499030..8668da467cd 100644
--- a/spec/models/category_spec.rb
+++ b/spec/models/category_spec.rb
@@ -538,7 +538,7 @@ describe Category do
     it 'is deleted correctly' do
       @category.destroy
       expect(Category.exists?(id: @category_id)).to be false
-      expect(Topic.exists?(id: @topic_id)).to be false
+      expect(Topic.with_deleted.where.not(deleted_at: nil).exists?(id: @topic_id)).to be true
       expect(SiteSetting.shared_drafts_category).to be_blank
     end