2015-08-16 34 views
2

按照“使用Rails 4进行敏捷Web开发”的指导。 它涵盖产品目录的缓存,只重新渲染已更改的产品。尽管没有模型更改,但Rails部分缓存显示视图更改

我编辑(配置/环境/ development.rb):

config.action_controller.perform_caching = true 

添加代码返回最近更新的产品: (应用程序/模型/ product.rb)

def self.latest 
    Product.order(:updated_at).latest 
end 

最后更新了缓存的商店索引: (app/views/store/index.html.erb)

<h1>Your Pragmatic Catalog</h1> 
<% cache ['store', Product.latest] do %> 
    <% @products.each do |product| %> 
    <% cache ['entry', product] do %> 
     <div class="entry"> 
     <%= image_tag(product.image_url) %> 
     <h3><%= product.title %></h3> 
     <%= sanitize(product.description) %> 
     <div class="price_line"> 
      <span class="price"><%= number_to_currency(product.price) %></span> 
     </div> 
     </div> 
    <% end %> 
    <% end %> 
<% end %> 

本书指出测试缓存是否有效的唯一方法是更改​​视图,因此我所做的只是在一个或两个缓存标记中添加一些lorem ipsum,但浏览器会立即显示刷新的变化......令人沮丧!任何线索?

+0

你有'Product.latest'上的一个错误,这就是自我调用。如果没有错误出现,那么你可能有一个'Product.order(:updated_at).last(10)'。 – dgilperez

+0

可能很明显,但是在更改环境文件后是否重新启动了服务器? – faron

回答

1

尝试使用

<% cache ['v1', Product.order(updated_at: :desc).last] do %> 

代替

<% cache ['store', Product.latest] do %> 
1

用于收集您的缓存键没有改变。发生这种情况是因为cache ['store', Product.latest]并不像您期望的那么聪明。如果你看看日志,你会看到使用的缓存键是一个文字,包括类似ActiveRecord :: Relation :: Products

使用最后的updated_atcache ['store', Product.latest.max(:updated_at)]以获得更好的结果。

在Rails 5中,由于几周前的the addition of cache_key to ActiveRecord::Relation会更容易。