我也有一定的要求看櫃檯的變化。在挖掘rails源代碼之後,通過直接的SQL更新來改變counter_column。換句話說,它不會觸發任何回調(在你的情況下,當Post更新時它不會觸發Author模型中的任何回調)。
from rails源代碼,counter_column也被after_update回調改變了。
我的做法是給軌道的一路上漲,由我更新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
什麼是在具有反緩存在所有那麼點? – 2012-01-25 12:55:26