FIX: delete synonyms in topics if target tag is already added.

FIX: delete synonyms in topics if target tag is already added.

Currently, while adding a synonym tag if both target and synonym tags are already available in a topic then it’s returning an error.

diff --git a/lib/discourse_tagging.rb b/lib/discourse_tagging.rb
index af34e95..5cd3ad7 100644
--- a/lib/discourse_tagging.rb
+++ b/lib/discourse_tagging.rb
@@ -423,7 +423,9 @@ module DiscourseTagging
       target_tag.synonyms << Tag.create(name: name)
     end
     successful = existing.select { |t| !t.errors.present? }
-    TopicTag.where(tag_id: successful.map(&:id)).update_all(tag_id: target_tag.id)
+    synonyms_ids = successful.map(&:id)
+    TopicTag.where(topic_id: target_tag.topics.with_deleted, tag_id: synonyms_ids).delete_all
+    TopicTag.where(tag_id: synonyms_ids).update_all(tag_id: target_tag.id)
     Scheduler::Defer.later "Update tag topic counts" do
       Tag.ensure_consistency!
     end
diff --git a/spec/components/discourse_tagging_spec.rb b/spec/components/discourse_tagging_spec.rb
index b8d328f..7ef3a20 100644
--- a/spec/components/discourse_tagging_spec.rb
+++ b/spec/components/discourse_tagging_spec.rb
@@ -517,6 +517,16 @@ describe DiscourseTagging do
       expect(tag2.reload.target_tag).to eq(tag1)
     end
 
+    it "can add an existing tag when both tags added to same topic" do
+      topic = Fabricate(:topic, tags: [tag1, tag2, tag3])
+      expect {
+        expect(DiscourseTagging.add_or_create_synonyms_by_name(tag1, [tag2.name])).to eq(true)
+      }.to_not change { Tag.count }
+      expect_same_tag_names(tag1.reload.synonyms, [tag2])
+      expect_same_tag_names(topic.reload.tags, [tag1, tag3])
+      expect(tag2.reload.target_tag).to eq(tag1)
+    end
+
     it "can add existing tag with wrong case" do
       expect {
         expect(DiscourseTagging.add_or_create_synonyms_by_name(tag1, [tag2.name.upcase])).to eq(true)

GitHub sha: ef37460c

This commit has been mentioned on Discourse Meta. There might be relevant details there:

https://meta.discourse.org/t/error-adding-tag-synonym-when-both-already-exist-on-a-topic/158080/6