diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb index 847d5b62d99..7fffed3b56e 100644 --- a/app/controllers/tags_controller.rb +++ b/app/controllers/tags_controller.rb @@ -112,17 +112,25 @@ class TagsController < ::ApplicationController end def search - query = DiscourseTagging.filter_allowed_tags( + category = params[:categoryId] ? Category.find_by_id(params[:categoryId]) : nil + + tags_with_counts = DiscourseTagging.filter_allowed_tags( self.class.tags_by_count(guardian, params.slice(:limit)), guardian, - { - for_input: params[:filterForInput], - term: params[:q], - category: params[:categoryId] ? Category.find_by_id(params[:categoryId]) : nil - } + { for_input: params[:filterForInput], term: params[:q], category: category } ) - tags = query.count.map {|t, c| { id: t, text: t, count: c } } + tags = tags_with_counts.count.map {|t, c| { id: t, text: t, count: c } } + + unused_tags = DiscourseTagging.filter_allowed_tags( + Tag.where(topic_count: 0), + guardian, + { for_input: params[:filterForInput], term: params[:q], category: category } + ) + + unused_tags.each do |t| + tags << { id: t.name, text: t.name, count: 0 } + end render json: { results: tags } end diff --git a/app/models/category.rb b/app/models/category.rb index 506950ec1f0..ffde109b906 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -318,6 +318,12 @@ SQL def allowed_tags=(tag_names) if self.tags.pluck(:name).sort != tag_names.sort self.tags = Tag.where(name: tag_names).all + if self.tags.size < tag_names.size + new_tag_names = tag_names - self.tags.map(&:name) + new_tag_names.each do |name| + self.tags << Tag.create(name: name) + end + end end end diff --git a/spec/integration/category_tag_spec.rb b/spec/integration/category_tag_spec.rb index 0c3c4fd95fd..358db1e0551 100644 --- a/spec/integration/category_tag_spec.rb +++ b/spec/integration/category_tag_spec.rb @@ -51,5 +51,10 @@ describe "category tag restrictions" do post = create_post(category: other_category, tags: [tag3.name, "newtag"]) expect(post.topic.tags.map(&:name).sort).to eq([tag3.name, "newtag"].sort) end + + it "can create tags when changing category settings" do + expect { other_category.update(allowed_tags: ['newtag']) }.to change { Tag.count }.by(1) + expect { other_category.update(allowed_tags: [tag1.name, 'tag-stuff', tag2.name, 'another-tag']) }.to change { Tag.count }.by(2) + end end end