Rails Fragment Caching不起作用

时间:2016-07-15 06:49:59

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

我试图添加片段缓存以加快网站性能。 现在,我在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" = $1 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" = $1  [["category_id", 3306]]
  Project Load (1.0ms)  SELECT  DISTINCT "projects".* FROM "projects" WHERE "projects"."category_id" = $1 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)

1 个答案:

答案 0 :(得分:0)

根据您的日志,看起来数据是从缓存填充的产品,并且没有针对产品触发查询。

views/projects/3670-20160715055333331671000/9b54e2d9c7ce230e3f6a333f00d549da

中间的数字是product_id,后跟产品记录的updated_at属性中的timestamp值。 Rails使用时间戳值来确保它不提供过时数据。如果updated_at的值已更改,则将生成新密钥(触发对数据库的查询)。然后Rails会为该密钥写一个新的缓存,并且永远不会再次使用写入旧密钥的旧缓存。 希望这有帮助!