使用 fresh_when 缓存活动记录关联

Caching active record associations with fresh_when

缓存 ActiveRecord 关联的最佳方式是什么?这是我在控制器中尝试做的事情:

def all_posts
  @posts = User.find(params[:id]).posts
  fresh_when @posts
end

每当将新的 post 添加到 user 模型时,我都需要清除缓存。

您的解决方案完美无缺。

如果您只是添加 posts,则有一个更高效的解决方案:您必须在 [=13= 的 belongs_to :user 部分添加 touch: true ] 模型。每次更改 post 并创建新的 post 时,ActiveRecord 都会触及 User 对象。实现后,您可以使用此控制器代码:

def all_posts
  user = User.find(params[:id])
  @posts = user.posts
  fresh_when user
end

从一个 user 生成缓存键比从多个 posts 生成缓存键快得多。

查看 http://www.xyzpub.com/en/ruby-on-rails/3.2/caching.html 以了解 Rails 中的缓存介绍。