我也有看柜台变化的要求。挖掘 Rails 源代码后,通过直接 SQL 更新更改 counter_column。换句话说,它不会触发任何回调(在您的情况下,它不会在发布更新时触发 Author 模型中的任何回调)。
从 Rails 源代码中,counter_column 也被 after_update 回调更改。
我的方法是让rails向上,自己更新counter_column:
class Post
belongs_to :author
after_update :update_author_posts_counter
def update_author_posts_counter
# need to update for both previous author and new author
# find_by will not raise exception if there isn't any record
author_was = Author.find_by(id: author_id_was)
if author_was
author_was.update_posts_count!
end
if author
author.update_posts_count!
end
end
end
class Author
has_many :posts
after_update :expires_cache, if: :posts_count_changed?
def expires_cache
# do whatever you want
end
def update_posts_count!
update(posts_count: posts.count)
end
end