【发布时间】:2015-08-19 07:53:04
【问题描述】:
我想使用 Redis 在我的 Rails 应用程序中进行一些低级缓存。 在控制器中,我通常使用它来获取所有书籍:
class BooksController < ApplicationController
def index
@books = Book.order(:title)
end
end
并且视图会对此进行迭代:
<ul>
- @books.each do |book|
<li>= "#{book.title} - #{book.author}"</li>
</ul>
现在我想要完全相同的结果,但随后被缓存。我已经安装并运行了 Redis。那么我应该像这样在控制器中使用cached_books 方法吗:
@books = Book.cached_books.order(:title)
让视图保持原样,或者在视图中使用book.cached_title 和book.cached_author 并让控制器保持原样?
cached_books 方法在 Book 模型中的外观如何?
class Book < ActiveRecord::Base
...
def cached_books
Rails.cache.fetch([self, "books"]) { books.to_a }
end
end
为简单起见,我暂时省略了过期策略,但显然它们需要存在。
【问题讨论】:
-
我不会在模型中添加缓存
-
只是检查一下:你读过guide about caching吗?
-
当然,但我正在寻找一个集合的特定模型缓存
标签: ruby-on-rails caching redis