A platform for community discussion. Free, open, simple.
DEV: Remove tag_id param in favour of tag param for topic creation with tags to allow tag creation (#37597)
Natalie Tay6cae7a3a7e0b
diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rbindex f25b8e51ee7..66adcd5e520 100644--- a/app/controllers/posts_controller.rb+++ b/app/controllers/posts_controller.rb@@ -970,6 +970,14 @@ class PostsController < ApplicationControllerresult[f] = params[f] if params.has_key?(f)end+ if result[:tags].present? && result[:tags].first.is_a?(String)+ Discourse.deprecate(+ "Passing tag names as strings to the tags param is deprecated, use tag objects ({id, name}) instead",+ since: "2026.01",+ drop_from: "2026.07",+ )+ end+# Stuff we can use in spam prevention pluginsresult[:ip_address] = request.remote_ipresult[:user_agent] = request.user_agentdiff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rbindex edfe02e721f..c144545f3a3 100644--- a/app/controllers/topics_controller.rb+++ b/app/controllers/topics_controller.rb@@ -447,9 +447,22 @@ class TopicsController < ApplicationControllerchanges.delete(:title) if topic.title == changes[:title]changes.delete(:category_id) if topic.category_id.to_i == changes[:category_id].to_i- if Tag.include_tags?- topic_tags = topic.tags.map(&:name).sort- changes.delete(:tags) if changes[:tags]&.sort == topic_tags+ if Tag.include_tags? && changes[:tags].present?+ incoming = changes[:tags]++ if incoming.first.is_a?(String)+ Discourse.deprecate(+ "Passing tag names as strings to the tags param is deprecated, use tag objects ({id, name}) instead",+ since: "2026.01",+ drop_from: "2026.07",+ )+ changes.delete(:tags) if incoming.sort == topic.tags.map(&:name).sort+ else+ has_new = incoming.any? { |t| t[:id].blank? }+ if !has_new && incoming.filter_map { |t| t[:id]&.to_i }.sort == topic.tags.pluck(:id).sort+ changes.delete(:tags)+ end+ endendsuccess = true@@ -475,18 +488,15 @@ class TopicsController < ApplicationControllertopic = Topic.find_by(id: params[:topic_id])guardian.ensure_can_edit_tags!(topic)- tags =- if params[:tag_ids].present?- params[:tag_ids].map(&:to_i)- else- params.require(:tags)- Discourse.deprecate(- "the tags param is deprecated, use tag_ids instead",- since: "2026.01",- drop_from: "2026.07",- )- params[:tags]- end+ tags = params[:tags] || []++ if tags.present? && tags.first.is_a?(String)+ Discourse.deprecate(+ "Passing tag names as strings to the tags param is deprecated, use tag objects ({id, name}) instead",+ since: "2026.01",+ drop_from: "2026.07",+ )+ endsuccess =PostRevisor.new(topic.first_post, topic).revise!(diff --git a/frontend/discourse/app/models/topic.js b/frontend/discourse/app/models/topic.jsindex b91818aaddc..3cd7bdfc162 100644--- a/frontend/discourse/app/models/topic.js+++ b/frontend/discourse/app/models/topic.js@@ -959,14 +959,6 @@ export default class Topic extends RestModel {}updateTags(tags) {- // send tag_ids when values are objects- if (tags?.every((t) => typeof t === "object")) {- return ajax(`/t/${this.id}/tags`, {- type: "PUT",- data: { tag_ids: tags.map((t) => t.id) },- });- }-return ajax(`/t/${this.id}/tags`, {type: "PUT",data: { tags: tags || [] },diff --git a/lib/discourse_tagging.rb b/lib/discourse_tagging.rbindex 1e1a81570ef..9f67727e6f9 100644--- a/lib/discourse_tagging.rb+++ b/lib/discourse_tagging.rb@@ -16,6 +16,27 @@ module DiscourseTagging@term_types ||= Enum.new(contains: 0, starts_with: 1)end+ # Sets tags for topic and allows new tags to be created if they do not exist.+ #+ # Accepts either an array of tag names (backward compatibility) or an array of hashes with :id and/or :name keys.+ #+ # @param topic [Topic] the topic to be tagged+ # @param guardian [Guardian] the guardian of the user performing the action+ # @param tags_param [Array<String>, Array<Hash>] an array of tag names or an array of+ # hashes with :id and/or :name keys (absence of id indicates new tag).+ def self.tag_topic(topic, guardian, tags_param)+ if tags_param.blank? || tags_param.first.is_a?(String)+ return tag_topic_by_names(topic, guardian, tags_param)+ end++ tag_ids = tags_param.filter_map { |t| t[:id]&.to_i }+ new_names = tags_param.filter_map { |t| t[:id].blank? && t[:name].presence }++ tag_names = new_names+ tag_names += Tag.where(id: tag_ids).pluck(:name) if tag_ids.present?+ tag_topic_by_names(topic, guardian, tag_names)+ end+def self.tag_topic_by_names(topic, guardian, tag_names_arg, append: false)if guardian.can_tag?(topic)tag_names = DiscourseTagging.tags_for_saving(tag_names_arg, guardian) || []diff --git a/lib/post_revisor.rb b/lib/post_revisor.rbindex 29e986c1208..11b97116989 100644--- a/lib/post_revisor.rb+++ b/lib/post_revisor.rb@@ -47,13 +47,7 @@ class PostRevisorprev_tags = topic.tags.map(&:name)return if tag_value.blank? && prev_tags.blank?- by_ids = tag_value.first.is_a?(Integer)- success =- if by_ids- DiscourseTagging.tag_topic_by_ids(topic, guardian, tag_value)- else- DiscourseTagging.tag_topic_by_names(topic, guardian, tag_value)- end+ success = DiscourseTagging.tag_topic(topic, guardian, tag_value)unless successcheck_result(false)diff --git a/lib/topic_creator.rb b/lib/topic_creator.rbindex d13ea6d26ba..cd086f8e81d 100644--- a/lib/topic_creator.rb+++ b/lib/topic_creator.rb@@ -28,10 +28,17 @@ class TopicCreatorcategory = find_categoryif category.present? && guardian.can_tag?(topic)tags =- if @opts[:tag_ids].present?- Tag.where(id: @opts[:tag_ids]).pluck(:name)+ if @opts[:tags].present?+ input = @opts[:tags]+ if input.first.is_a?(String)+ input+ else+ ids = input.filter_map { |t| t[:id]&.to_i }+ names = input.filter_map { |t| t[:id].blank? && t[:name].presence }+ Tag.where(id: ids).pluck(:name) + names+ endelse- @opts[:tags].presence || []+ []end# adds topic.errors@@ -195,22 +202,15 @@ class TopicCreatorenddef setup_tags(topic)- if @opts[:tag_ids].present?- valid_tags = DiscourseTagging.tag_topic_by_ids(topic, @guardian, @opts[:tag_ids])- if !valid_tags- if @opts[:skip_validations]- tag_names = Tag.where(id: @opts[:tag_ids]).pluck(:name)- DiscourseTagging.add_or_create_tags_by_name(topic, tag_names)- else- topic.errors.add(:base, :unable_to_tag)- rollback_from_errors!(topic)- end- end- elsif @opts[:tags].present?- valid_tags = DiscourseTagging.tag_topic_by_names(topic, @guardian, @opts[:tags])+ if @opts[:tags].present?+ tags = @opts[:tags]++ valid_tags = DiscourseTagging.tag_topic(topic, @guardian, tags)+if !valid_tagsif @opts[:skip_validations]- DiscourseTagging.add_or_create_tags_by_name(topic, @opts[:tags])+ all_names = tags.filter_map { |t| t.is_a?(String) ? t : t[:name] }+ DiscourseTagging.add_or_create_tags_by_name(topic, all_names)elsetopic.errors.add(:base, :unable_to_tag)rollback_from_errors!(topic)diff --git a/spec/lib/discourse_tagging_spec.rb b/spec/lib/discourse_tagging_spec.rbindex cb270271823..4f4c5f2af0f 100644--- a/spec/lib/discourse_tagging_spec.rb+++ b/spec/lib/discourse_tagging_spec.rb@@ -1680,6 +1680,59 @@ RSpec.describe DiscourseTagging doendend+ describe ".tag_topic" do+ fab!(:topic)+ fab!(:tag1) { Fabricate(:tag, name: "tag1") }+ fab!(:tag2) { Fabricate(:tag, name: "tag2") }++ it "allows tagging topics by an array of tag names" do+ valid = DiscourseTagging.tag_topic(topic, Guardian.new(admin), %w[tag1 tag2])+ expect(valid).to eq(true)+ expect(topic.reload.tags).to contain_exactly(tag1, tag2)+ end++ it "allows tagging topics by an array of hash with the id key" do+ valid =+ DiscourseTagging.tag_topic(+ topic,+ Guardian.new(admin),+ [{ id: tag1.id, name: "tHE wROnG nAme" }, { id: tag2.id, name: "tag2" }],+ )+ expect(valid).to eq(true)+ expect(topic.reload.tags).to contain_exactly(tag1, tag2)+ end++ it "allows tagging topics using new tags" do+ valid =+ DiscourseTagging.tag_topic(+ topic,+ Guardian.new(admin),+ [{ name: "new-tag-a" }, { name: "new-tag-b" }],+ )+ expect(valid).to eq(true)+ expect(topic.reload.tags.pluck(:name)).to contain_exactly("new-tag-a", "new-tag-b")+ end++ it "can tag topics using old and new tags" do+ valid =+ DiscourseTagging.tag_topic(+ topic,+ Guardian.new(admin),+ [{ id: tag1.id, name: "tag1" }, { name: "brand-new" }],+ )+ expect(valid).to eq(true)+ expect(topic.reload.tags.pluck(:name)).to contain_exactly("tag1", "brand-new")+ end++ it "clears tags when given blank input" do+ topic.tags = [tag1]+ topic.save!+ valid = DiscourseTagging.tag_topic(topic, Guardian.new(admin), [])+ expect(valid).to eq(true)+ expect(topic.reload.tags).to be_empty+ end+ end+describe "tag_topic_by_ids" dofab!(:topic)fab!(:tag1) { Fabricate(:tag, name: "tag1") }diff --git a/spec/lib/post_revisor_spec.rb b/spec/lib/post_revisor_spec.rbindex e8872576892..8f2095b063c 100644--- a/spec/lib/post_revisor_spec.rb+++ b/spec/lib/post_revisor_spec.rb@@ -227,10 +227,13 @@ describe PostRevisor doexpect { post_revisor.revise!(admin, tags: ["new-tag"]) }.not_to change { Post.count }end- it "accepts tags as integer IDs" do+ it "edits a topic's tags" dotag = Fabricate(:tag)- post_revisor.revise!(admin, tags: [tag.id])+ post_revisor.revise!(admin, tags: [{ id: tag.id, name: "outdated" }])expect(post.topic.reload.tags).to contain_exactly(tag)++ post_revisor.revise!(admin, tags: ["a-whole-new-tag"])+ expect(post.topic.reload.tags).to match_array([have_attributes(name: "a-whole-new-tag")])enddescribe "when `create_post_for_category_and_tag_changes` site setting is enabled" do@@ -1070,16 +1073,16 @@ describe PostRevisor dopost.topic.update!(tags: [tag1])- post_revisor.revise!(admin, tags: [tag2.id])+ post_revisor.revise!(admin, tags: [{ id: tag2.id, name: tag2.name }])modifications = post.post_revisions.last.modificationsexpect(modifications["tags"]).to eq([["existing-tag"], ["another-tag"]])end- it "tracks tag changes from empty to tagged using IDs (integers)" do+ it "tracks tag changes from empty to tagged using objects" dotag = Fabricate(:tag, name: "new-via-id")- post_revisor.revise!(admin, tags: [tag.id])+ post_revisor.revise!(admin, tags: [{ id: tag.id, name: tag.name }])modifications = post.post_revisions.last.modificationsexpect(modifications["tags"]).to eq([[], ["new-via-id"]])diff --git a/spec/lib/topic_creator_spec.rb b/spec/lib/topic_creator_spec.rbindex ac321300610..b771acfb324 100644--- a/spec/lib/topic_creator_spec.rb+++ b/spec/lib/topic_creator_spec.rb@@ -122,23 +122,37 @@ RSpec.describe TopicCreator doendcontext "with regular tags" do- it "user can add tags to topic" do+ it "can add tag names to topic" dotopic =TopicCreator.create(user, Guardian.new(user), valid_attrs.merge(tags: [tag1.name]))expect(topic).to be_validexpect(topic.tags.length).to eq(1)end- it "user can add tags to topic using tag_ids" do+ it "can add tags to topic" dotopic =TopicCreator.create(user,Guardian.new(user),- valid_attrs.merge(tag_ids: [tag1.id, tag2.id]),+ valid_attrs.merge(+ tags: [{ id: tag1.id, name: tag1.name }, { id: tag2.id, name: tag2.name }],+ ),)expect(topic).to be_validexpect(topic.tags).to contain_exactly(tag1, tag2)end++ it "can create new tags" do+ SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]+ topic =+ TopicCreator.create(+ user,+ Guardian.new(user),+ valid_attrs.merge(tags: [{ id: tag1.id, name: tag1.name }, { name: "brand-new" }]),+ )+ expect(topic).to be_valid+ expect(topic.tags).to contain_exactly(have_attributes(name: "brand-new"), tag1)+ endendcontext "when assigned via matched watched words" dodiff --git a/spec/requests/posts_controller_spec.rb b/spec/requests/posts_controller_spec.rbindex 5d841ef9ab7..baf4fdae8ed 100644--- a/spec/requests/posts_controller_spec.rb+++ b/spec/requests/posts_controller_spec.rb@@ -1603,6 +1603,27 @@ RSpec.describe PostsController doexpect(json["errors"]).to be_presentend+ describe "tagging by name" do+ it "can create a post with a tag when tagging is enabled" do+ SiteSetting.tagging_enabled = true+ tag = Fabricate(:tag)++ logger =+ track_log_messages do+ post "/posts.json",+ params: {+ raw: "this is the test content",+ title: "this is the test title for the topic",+ tags: [tag.name],+ }+ end++ expect(response.status).to eq(200)+ expect(Post.last.topic.tags.count).to eq(1)+ expect(logger.warnings.join("\n")).to include("tag names as strings")+ end+ end+it "can create a post with a tag when tagging is enabled" doSiteSetting.tagging_enabled = truetag = Fabricate(:tag)@@ -1611,11 +1632,11 @@ RSpec.describe PostsController doparams: {raw: "this is the test content",title: "this is the test title for the topic",- tags: [tag.name],+ tags: [{ id: tag.id, name: tag.name }],}expect(response.status).to eq(200)- expect(Post.last.topic.tags.count).to eq(1)+ expect(Post.last.topic.tags).to contain_exactly(tag)endit "creates the topic and post with the right attributes" dodiff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rbindex f5f9295f48e..94adc855ce5 100644--- a/spec/requests/topics_controller_spec.rb+++ b/spec/requests/topics_controller_spec.rb@@ -2110,66 +2110,100 @@ RSpec.describe TopicsController docontext "with tags" dobefore { SiteSetting.tagging_enabled = true }- it "can add a tag to topic" do- expect do- put "/t/#{topic.slug}/#{topic.id}.json", params: { tags: [tag.name] }- end.to change { topic.reload.first_post.revisions.count }.by(1)+ describe "tagging by name" do+ it "can add a tag to topic" do+ expect do+ put "/t/#{topic.slug}/#{topic.id}.json", params: { tags: [tag.name] }+ end.to change { topic.reload.first_post.revisions.count }.by(1)- expect(response.status).to eq(200)- expect(topic.tags.pluck(:id)).to contain_exactly(tag.id)- end+ expect(response.status).to eq(200)+ expect(topic.tags.pluck(:id)).to contain_exactly(tag.id)+ end- it "can create a tag" do- SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]- expect do- put "/t/#{topic.slug}/#{topic.id}.json", params: { tags: ["newtag"] }- end.to change { topic.reload.first_post.revisions.count }.by(1)+ it "can create a tag" do+ SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]+ expect do+ put "/t/#{topic.slug}/#{topic.id}.json", params: { tags: ["newtag"] }+ end.to change { topic.reload.first_post.revisions.count }.by(1)- expect(response.status).to eq(200)- expect(topic.reload.tags.pluck(:name)).to contain_exactly("newtag")- end+ expect(response.status).to eq(200)+ expect(topic.reload.tags.pluck(:name)).to contain_exactly("newtag")+ end- it "can change the category and create a new tag" do- SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]- expect do- put "/t/#{topic.slug}/#{topic.id}.json",- params: {- tags: ["newtag"],- category_id: category.id,- }- end.to change { topic.reload.first_post.revisions.count }.by(1)+ it "can change the category and create a new tag" do+ SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]+ expect do+ put "/t/#{topic.slug}/#{topic.id}.json",+ params: {+ tags: ["newtag"],+ category_id: category.id,+ }+ end.to change { topic.reload.first_post.revisions.count }.by(1)- expect(response.status).to eq(200)- expect(topic.reload.tags.pluck(:name)).to contain_exactly("newtag")- end+ expect(response.status).to eq(200)+ expect(topic.reload.tags.pluck(:name)).to contain_exactly("newtag")+ end- it "can add a tag to wiki topic" do- SiteSetting.edit_wiki_post_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]- topic.first_post.update!(wiki: true)- sign_in(user_2)+ it "can add a tag to wiki topic" do+ SiteSetting.edit_wiki_post_allowed_groups = Group::AUTO_GROUPS[:trust_level_2]+ topic.first_post.update!(wiki: true)+ sign_in(user_2)- expect do- put "/t/#{topic.id}/tags.json", params: { tags: [tag.name] }- end.not_to change { topic.reload.first_post.revisions.count }+ expect do+ put "/t/#{topic.id}/tags.json", params: { tags: [tag.name] }+ end.not_to change { topic.reload.first_post.revisions.count }- expect(response.status).to eq(403)- user_2.groups << Group.find_by(name: "trust_level_2")+ expect(response.status).to eq(403)+ user_2.groups << Group.find_by(name: "trust_level_2")++ expect do put "/t/#{topic.id}/tags.json", params: { tags: [tag.name] } end.to change {+ topic.reload.first_post.revisions.count+ }.by(1)++ expect(response.status).to eq(200)+ expect(topic.tags.pluck(:id)).to contain_exactly(tag.id)+ end++ it "can remove a tag" do+ topic.tags << tag++ expect do+ put "/t/#{topic.slug}/#{topic.id}.json", params: { tags: [""] }+ end.to change { topic.reload.first_post.revisions.count }.by(1)++ expect(response.status).to eq(200)+ expect(topic.tags).to eq([])+ end++ it "does not cause a revision when tags have not changed" do+ topic.tags << tag++ expect do+ put "/t/#{topic.slug}/#{topic.id}.json", params: { tags: [tag.name] }+ end.not_to change { topic.reload.first_post.revisions.count }++ expect(response.status).to eq(200)+ end+ end- expect do put "/t/#{topic.id}/tags.json", params: { tags: [tag.name] } end.to change {- topic.reload.first_post.revisions.count- }.by(1)+ it "can update tags" do+ expect do+ put "/t/#{topic.id}/tags.json", params: { tags: [{ id: tag.id, name: tag.name }] }+ end.to change { topic.reload.first_post.revisions.count }.by(1)expect(response.status).to eq(200)expect(topic.tags.pluck(:id)).to contain_exactly(tag.id)end- it "can update tags using tag_ids" do- expect do put "/t/#{topic.id}/tags.json", params: { tag_ids: [tag.id] } end.to change {- topic.reload.first_post.revisions.count- }.by(1)+ it "can create a new tag" do+ SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]++ expect do+ put "/t/#{topic.id}/tags.json", params: { tags: [{ name: "brand-new" }] }+ end.to change { topic.reload.first_post.revisions.count }.by(1)expect(response.status).to eq(200)- expect(topic.tags.pluck(:id)).to contain_exactly(tag.id)+ expect(topic.reload.tags.pluck(:name)).to contain_exactly("brand-new")endit "does not remove tag if no params is given" do@@ -2182,25 +2216,48 @@ RSpec.describe TopicsController doexpect(response.status).to eq(200)end- it "can remove a tag" do+ it "does not cause a revision when tags have not changed" do+ topic.tags << tag++ expect do+ put "/t/#{topic.slug}/#{topic.id}.json",+ params: {+ tags: [{ id: tag.id, name: tag.name }],+ }+ end.not_to change { topic.reload.first_post.revisions.count }++ expect(response.status).to eq(200)+ end++ it "can add a tag on topic update" do+ SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]topic.tags << tagexpect do- put "/t/#{topic.slug}/#{topic.id}.json", params: { tags: [""] }+ put "/t/#{topic.slug}/#{topic.id}.json",+ params: {+ tags: [{ id: tag.id, name: tag.name }, { name: "new-tag" }],+ }end.to change { topic.reload.first_post.revisions.count }.by(1)expect(response.status).to eq(200)- expect(topic.tags).to eq([])+ expect(topic.reload.tags.pluck(:name)).to contain_exactly(tag.name, "new-tag")end- it "does not cause a revision when tags have not changed" do+ it "can remove a tag on topic update" do+ tag2 = Fabricate(:tag)topic.tags << tag+ topic.tags << tag2expect do- put "/t/#{topic.slug}/#{topic.id}.json", params: { tags: [tag.name] }- end.not_to change { topic.reload.first_post.revisions.count }+ put "/t/#{topic.slug}/#{topic.id}.json",+ params: {+ tags: [{ id: tag.id, name: tag.name }],+ }+ end.to change { topic.reload.first_post.revisions.count }.by(1)expect(response.status).to eq(200)+ expect(topic.reload.tags).to contain_exactly(tag)endend