diff --git a/app/models/category.rb b/app/models/category.rb index 520c86c07f6..37142c7f861 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -46,6 +46,9 @@ class Category < ActiveRecord::Base after_update :rename_category_definition, if: :name_changed? + after_create :delete_category_permalink + after_update :create_category_permalink, if: :slug_changed? + after_save :publish_discourse_stylesheet has_one :category_search_data @@ -447,6 +450,24 @@ SQL end end + def create_category_permalink + old_slug = changed_attributes["slug"] + if self.parent_category + Permalink.create(url: "c/#{self.parent_category.slug}/#{old_slug}", category_id: id) + else + Permalink.create(url: "c/#{old_slug}", category_id: id) + end + end + + def delete_category_permalink + if self.parent_category + permalink = Permalink.find_by_url("c/#{self.parent_category.slug}/#{slug}") + else + permalink = Permalink.find_by_url("c/#{slug}") + end + permalink.destroy if permalink + end + def publish_discourse_stylesheet DiscourseStylesheets.cache.clear end diff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rb index 4506c0bbe36..c35875b0b8b 100644 --- a/spec/models/category_spec.rb +++ b/spec/models/category_spec.rb @@ -316,6 +316,30 @@ describe Category do expect { @category.update_attributes(name: 'Troutfishing', topic_id: nil) }.to_not raise_error end + it "creates permalink when category slug is changed" do + @category.update_attributes(slug: 'new-category') + expect(Permalink.count).to eq(1) + end + + it "creates permalink when sub category slug is changed" do + sub_category = Fabricate(:category, slug: 'sub-category', parent_category_id: @category.id) + sub_category.update_attributes(slug: 'new-sub-category') + expect(Permalink.count).to eq(1) + end + + it "deletes permalink when category slug is reused" do + Fabricate(:permalink, url: "/c/bikeshed-category") + Fabricate(:category, slug: 'bikeshed-category') + expect(Permalink.count).to eq(0) + end + + it "deletes permalink when sub category slug is reused" do + Fabricate(:permalink, url: "/c/main-category/sub-category") + main_category = Fabricate(:category, slug: 'main-category') + Fabricate(:category, slug: 'sub-category', parent_category_id: main_category.id) + expect(Permalink.count).to eq(0) + end + it "should not set its description topic to auto-close" do category = Fabricate(:category, name: 'Closing Topics', auto_close_hours: 1) expect(category.topic.auto_close_at).to be_nil