From efb116d2bd4d1e02df9ddf79316112e0555b4c1e Mon Sep 17 00:00:00 2001 From: Blake Erickson Date: Wed, 12 Oct 2022 11:09:45 -0600 Subject: [PATCH] FIX: Reset related site settings on general category delete (#18548) * FIX: Reset related site settings on general category delete If the new seeded General category is deleted we also need to delete the corresponding site setting for it so that we don't try and reference it. This fixes a bug in the category dropdown composer. This change creates the `clear_related_site_settings` after destroy hook that could also be used by other features in the future, like maybe when we have a `default_category_id` site_setting. Looks like if `nil` out a site setting it is set to `0`? ``` [9] pry(main)> SiteSetting.general_category_id = nil SiteSetting Load (0.4ms) SELECT "site_settings".* FROM "site_settings" WHERE "site_settings"."name" = 'general_category_id' LIMIT 1 => nil [10] pry(main)> SiteSetting.general_category_id => 0 ``` That is why the tests check if the value is `< 1` and not `nil`. * Use -1 instead of nil because it is the default --- app/models/category.rb | 7 +++++++ spec/models/category_spec.rb | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/app/models/category.rb b/app/models/category.rb index adafc49a0f..0efbb5f3ed 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -70,6 +70,7 @@ class Category < ActiveRecord::Base after_create :create_category_definition after_destroy :trash_category_definition + after_destroy :clear_related_site_settings before_save :apply_permissions before_save :downcase_email @@ -312,6 +313,12 @@ class Category < ActiveRecord::Base self.topic&.trash! end + def clear_related_site_settings + if self.id == SiteSetting.general_category_id + SiteSetting.general_category_id = -1 + end + 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 942b38180c..da0cf3bb4a 100644 --- a/spec/models/category_spec.rb +++ b/spec/models/category_spec.rb @@ -1286,4 +1286,16 @@ RSpec.describe Category do end end end + + describe '#deleting the general category' do + fab!(:category) { Fabricate(:category) } + + it 'should empty out the general_category_id site_setting' do + SiteSetting.general_category_id = category.id + category.destroy + + expect(SiteSetting.general_category_id).to_not eq(category.id) + expect(SiteSetting.general_category_id).to be < 1 + end + end end