Rails 片段缓存不起作用

Rails Fragment Caching doesn't work

我试图添加片段缓存以加快网站性能。 现在,我在 development 模式下测试了它,所以我改变了这个

#environments/developments.rb
config.action_controller.perform_caching = true

并在 erb

<% @projects.each do |project| %>
    <% cache project do %>
        <%= link_to "#{project.name}", category_project_path(@category, project) %>
        <br>
    <% end %>
<% end %>

不过,好像不行。每次我刷新页面时,它都会在终端中再次显示查询。

我以为第一次只会查询一次,还是我理解错了缓存的概念?

Processing by CategoriesController#show as HTML
  Parameters: {"id"=>"3306"}
  Category Load (0.4ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" =  LIMIT 1  [["id", 3306]]
  Project Load (0.5ms)  SELECT "projects".* FROM "projects" WHERE "projects"."category_id" IN (3306)
   (0.4ms)  SELECT DISTINCT COUNT(DISTINCT "projects"."id") FROM "projects" WHERE "projects"."category_id" =   [["category_id", 3306]]
  Project Load (1.0ms)  SELECT  DISTINCT "projects".* FROM "projects" WHERE "projects"."category_id" =  LIMIT 10 OFFSET 0  [["category_id", 3306]]
  Cache digest for app/views/categories/show.html.erb: 9b54e2d9c7ce230e3f6a333f00d549da
Read fragment views/projects/3670-20160715055333331671000/9b54e2d9c7ce230e3f6a333f00d549da (0.2ms)
  Cache digest for app/views/categories/show.html.erb: 9b54e2d9c7ce230e3f6a333f00d549da
Read fragment views/projects/3677-20160715055334439274000/9b54e2d9c7ce230e3f6a333f00d549da (0.2ms)
  Cache digest for app/views/categories/show.html.erb: 9b54e2d9c7ce230e3f6a333f00d549da
Read fragment views/projects/3678-20160715055334446172000/9b54e2d9c7ce230e3f6a333f00d549da (0.2ms)
  Cache digest for app/views/categories/show.html.erb: 9b54e2d9c7ce230e3f6a333f00d549da
Read fragment views/projects/3689-20160715055334536421000/9b54e2d9c7ce230e3f6a333f00d549da (0.1ms)
  Rendered categories/show.html.erb within layouts/application (8.7ms)
Completed 200 OK in 31ms (Views: 26.0ms | ActiveRecord: 2.3ms)

根据您的日志,产品数据似乎是从缓存中填充的,并且没有触发产品查询。

views/projects/3670-20160715055333331671000/9b54e2d9c7ce230e3f6a333f00d549da

中间的数字是 product_id 后跟产品记录的 updated_at 属性中的时间戳值。 Rails 使用时间戳值来确保它没有提供过时的数据。如果 updated_at 的值发生变化,将生成一个新键(触发对数据库的查询)。然后Rails会向那个key写入一个新的缓存,而写入旧key的旧缓存将永远不会再被使用。 希望对您有所帮助!