配置 envirement/development.rbhtml
config.action_controller.perform_caching = true
找到視圖文件緩存
<% @customers.each do |customer| %> <%= render "customers/customer", customer: customer %> <% end %>
在視圖文件中使用緩存customers/_cutomer.html.erbapp
<% cache customer do %> <tr> <td><%= customer.name %></td> <td><%= customer.address %></td> <td> <table> <tr> <th> product name </th> </tr> <% customer.products.each do |prod| %> <%= render "customers/product", prod: prod %> <% end %> </table> </td> </tr> <% end %> <% customer.products.each do |prod| %> <%= render "customers/product", prod: prod %> <% end %> cache product <% cache prod do %> <tr> <td><%= prod.pro_name %></td> </tr> <% end %>
結構code
第一次瀏覽頁面的結果:orm
Started GET "/customers" for 127.0.0.1 at 2013-10-04 18:25:24 +0700 Processing by CustomersController#index as HTML Customer Load (0.6ms) SELECT "customers".* FROM "customers" Cache digest for customers/product.html: c5fb55246a3129b956535ab434389e0d Cache digest for customers/_customer.html: fbdda3154e8c043835599ee5c90b684e Read fragment views/customers/1-20131004104943753806000/fbdda3154e8c043835599ee5c90b684e (0.2ms) Rendered customers/_customer.html.erb (4.8ms) Read fragment views/customers/2-20131004102544448583000/fbdda3154e8c043835599ee5c90b684e (0.1ms) Rendered customers/_customer.html.erb (0.5ms) Read fragment views/customers/3-20131004112520652109000/fbdda3154e8c043835599ee5c90b684e (0.1ms) Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."customer_id" = ? [["customer_id", 3]] Write fragment views/customers/3-20131004112520652109000/fbdda3154e8c043835599ee5c90b684e (0.6ms) Rendered customers/_customer.html.erb (17.7ms) Rendered customers/index.html.erb within layouts/application (29.5ms) Completed 200 OK in 36ms (Views: 33.5ms | ActiveRecord: 1.3ms)
刷新頁面獲得的結構htm
Started GET "/customers" for 127.0.0.1 at 2013-10-04 18:28:55 +0700 Processing by CustomersController#index as HTML Customer Load (0.2ms) SELECT "customers".* FROM "customers" Read fragment views/customers/1-20131004104943753806000/fbdda3154e8c043835599ee5c90b684e (0.2ms) Rendered customers/_customer.html.erb (0.9ms) Read fragment views/customers/2-20131004102544448583000/fbdda3154e8c043835599ee5c90b684e (0.8ms) Rendered customers/_customer.html.erb (1.9ms) Read fragment views/customers/3-20131004112520652109000/fbdda3154e8c043835599ee5c90b684e (0.1ms) Rendered customers/_customer.html.erb (0.5ms) Rendered customers/index.html.erb within layouts/application (8.1ms) Completed 200 OK in 13ms (Views: 11.9ms | ActiveRecord: 0.2ms)
=> 渲染時間從33ms降到了11msrem