From 81e873138fa2a4d4aed2d81892179b3cf2913917 Mon Sep 17 00:00:00 2001 From: Neil Lalonde Date: Wed, 21 Feb 2018 12:35:53 -0500 Subject: [PATCH] FIX: error when deleting a tag associated with a deleted topic --- app/models/topic_tag.rb | 4 ++-- spec/models/tag_spec.rb | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/app/models/topic_tag.rb b/app/models/topic_tag.rb index f0996d1c9d7..067e1f79bf1 100644 --- a/app/models/topic_tag.rb +++ b/app/models/topic_tag.rb @@ -3,7 +3,7 @@ class TopicTag < ActiveRecord::Base belongs_to :tag, counter_cache: "topic_count" after_create do - if topic.category_id + if topic&.category_id if stat = CategoryTagStat.where(tag_id: tag_id, category_id: topic.category_id).first stat.increment!(:topic_count) else @@ -13,7 +13,7 @@ class TopicTag < ActiveRecord::Base end after_destroy do - if topic.category_id + if topic&.category_id if stat = CategoryTagStat.where(tag_id: tag_id, category: topic.category_id).first stat.topic_count == 1 ? stat.destroy : stat.decrement!(:topic_count) end diff --git a/spec/models/tag_spec.rb b/spec/models/tag_spec.rb index 6cea43f3052..06287133a5d 100644 --- a/spec/models/tag_spec.rb +++ b/spec/models/tag_spec.rb @@ -15,6 +15,13 @@ describe Tag do SiteSetting.min_trust_level_to_tag_topics = 0 end + it "can delete tags on deleted topics" do + tag = Fabricate(:tag) + topic = Fabricate(:topic, tags: [tag]) + topic.trash! + expect { tag.destroy }.to change { Tag.count }.by(-1) + end + describe '#tags_by_count_query' do it "returns empty hash if nothing is tagged" do expect(described_class.tags_by_count_query.count(Tag::COUNT_ARG)).to eq({})