【发布时间】:2019-11-16 12:29:31
【问题描述】:
我刚刚开始为我的应用程序进行缓存,但有点卡住了。我有一个依赖于范围的查询。范围收集页面上创建的最后 (x) 个帖子。
Rails.cache.fetch('homepage/posts') do
posts = Post.by_latest
render json: posts
end
这是我很难理解的。由于我想确保网站显示最新的帖子,我不想手动设置过期时间或日期。相反,我想在创建或销毁新帖子时使缓存过期。这是另一个困境。我想在我的 Post 模型中进行回调,但是当我想使其他键的缓存过期但都想完成同样的事情时,事情变得有点混乱。
def flush_cache
Rails.cache.delete('homepage/posts')
Rails.cache.delete('posts')
...
end
我想以更多的动态方法刷新缓存,就像使用单个对象一样...其中缓存键由对象的updated_at 属性组成,并且在修改时过期。不过,我发现很难收集。从查询中生成缓存键会导致查询本身,从而破坏缓存的整体目的:
Rails.cache.fetch(Post.by_latest.cache_key) do
posts = Post.by_latest
render json: posts
end
任何帮助将不胜感激。
【问题讨论】:
标签: ruby-on-rails caching