ruby-on-railscachingfragment-caching

Rails Fragment Caching doesn't work


I was trying to add fragment caching to speed up website performance. Now, I tested it in development mode, so I change this

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

And in erb

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

However, it seems not work. Every time I refresh the page, it showed query again in terminal.

I thought it would only query once in first time, or I've misunderstood the concept of cache?

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)

Solution

  • According to your logs it looks like data is product is populated from the cache and no query is fired for product.

    views/projects/3670-20160715055333331671000/9b54e2d9c7ce230e3f6a333f00d549da
    

    The number in the middle is the product_id followed by the timestamp value in the updated_at attribute of the product record. Rails uses the timestamp value to make sure it is not serving stale data. If the value of updated_at has changed, a new key will be generated(fires query to database). Then Rails will write a new cache to that key, and the old cache written to the old key will never be used again. Hope this help!