【问题标题】:Rails partial caching is showing view changes despite no model changes尽管没有模型更改,Rails 部分缓存仍显示视图更改
【发布时间】:2015-11-09 10:02:39
【问题描述】:

遵循“使用 Rails 4 进行敏捷 Web 开发”中的指南。 它涵盖了产品目录的缓存,以仅重新呈现已更改的产品。

我编辑了(config/environments/development.rb):

config.action_controller.perform_caching = true

添加代码以返回最近更新的产品: (app/models/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,但浏览器会立即显示刷新时的更改...令人沮丧!有什么线索吗?

【问题讨论】:

  • 你在Product.latest 上遇到了一个错误,它在调用它自己。如果没有出现错误,您可能有一个Product.order(:updated_at).last(10)
  • 可能很明显,但是您在更改环境文件后是否重新启动了服务器?

标签: ruby-on-rails ruby-on-rails-4 caching


【解决方案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,这将变得更容易。

【讨论】:

    【解决方案2】:

    尝试使用

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

    而不是

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

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 1970-01-01
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2016-11-10
      • 1970-01-01
      相关资源
      最近更新 更多