我想使用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
爲了簡單起見,我暫時忽略了過期的策略,但顯然他們需要在那裏。
我不會在模型 – apneadiving
只是檢查添加緩存:你看了(HTTP [關於緩存指南]://guides.rubyonrails .ORG/caching_with_rails.html)? – zwippie
當然,但我正在尋找特定的模型緩存集合 – John