分享 [译] 简单三步使用计数器缓存

rennyallen · 2017年01月08日 · 2278 次阅读

我最近开始在 Rails 中使用计数器缓存。然而这个上手起来要比指南里写的难一点。

指南里这样写的:

缓存关联对象的数量。例如,posts 表中的 comments_count 字段,缓存每篇文章的评论数;

英文版:

Used to cache the number of belonging objects on associations. For example, a comments_count column in a Post class that has many instances of Comment will cache the number of existent comments for each post.

虽然 Rails 内置机制做了困难的这部分,但你仍然需要做一些步骤否则它无法工作。以下是你要让计数器缓存工作需要做的一些事情。

我们使用和指南里一样的示例:我们想要计算一篇博客文章里的评论数量。

model 的定义像这样:

class Post < ActiveRecord::Base
  has_many :comments
end

class Comments < ActiveRecord::Base
  belongs_to :post
end

你需要做的第一件事是加一个 comments_count column 到 Post model 里。你可以用 migration 来做这个。运行了 migration 之后你还需要告诉 rails,这个 column 应该被用来当做计数缓存:

belongs_to :post, :counter_cache => true

剩下的问题是,如果之前数据库里已经有了 posts 和 comments 那么这个计数器是关闭的。这是因为当你创建或删除 model 的一个实例时计数器缓存增加或减少了。你可以像这样给 posts 重置计数器:

Post.find_each { |post| Post.reset_counters(post.id, :comments) }

可以把这个写成 rake task,那样当你的缓存计数出问题时你就可以运行它。

原文分享出来,欢迎大家交流指正。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号