diff --git a/app/models/tag.rb b/app/models/tag.rb index 26519fff8..b061c36a0 100644 --- a/app/models/tag.rb +++ b/app/models/tag.rb @@ -21,7 +21,8 @@ class Tag < ApplicationRecord validates :name, uniqueness: true, tag_name: true, on: :create validates_inclusion_of :category, in: TagCategory.category_ids - after_save :update_category_cache, if: ->(rec) { rec.saved_change_to_attribute?(:category)} + before_save :update_category_cache, if: :category_changed? + before_save :update_category_post_counts, if: :category_changed? module ApiMethods def to_legacy_json diff --git a/test/unit/tag_test.rb b/test/unit/tag_test.rb index 81f71de40..a01458075 100644 --- a/test/unit/tag_test.rb +++ b/test/unit/tag_test.rb @@ -208,6 +208,17 @@ class TagTest < ActiveSupport::TestCase assert_equal(0, tag.reload.category) end + should "update post tag counts when the category is changed" do + post = FactoryBot.create(:post, tag_string: "test") + assert_equal(1, post.tag_count_general) + assert_equal(0, post.tag_count_character) + + tag = Tag.find_or_create_by_name("char:test") + post.reload + assert_equal(0, post.tag_count_general) + assert_equal(1, post.tag_count_character) + end + should "be created when one doesn't exist" do assert_difference("Tag.count", 1) do tag = Tag.find_or_create_by_name("hoge")