# 启用或禁用 cache
| bin/rails dev:cache #=> Development mode is now being cached. | |
| # 再次执行上述命令会禁用缓存 | 
# 在模版中使用 cache 方法
- 将原先的代码逻辑包裹在 cache 方法的代码块中。
- 当数据发生变化的时候,Rails 会自动进行处理(包括缓存的存储、失效等问题)。
- 当 Rails 使用缓存数据的时候,服务器的输出信息中会看到 Read fragment字样。
- 如果数据发生了变化,服务器输出信息中会看到多行 Read fragment字样,同时有一行或多行Write fragment字样。
- 缓存数据触发更新的条件:待渲染数据对应的数据库表中的 updated_at字段的值发生了变化,也就是说在更新数据时,如果该记录的 updated_at 字段没有更新,那么之后渲染的数据仍然是之前缓存的旧数据。
| <%# 缓存@products实例变量中的数据,这是一个产品列表 %> | |
| <% cache @products do %> | |
| <% @products.each do |product| %> | |
| <%# 缓存@product实例变量中的数据 %> | |
| <% cache product do %> | |
| <div class="entry"> | |
| <%= image_tag(product.image_url) %> | |
| <h3><%= product.title %></h3> | |
| <%= sanitize(product.description) %> | |
| <div class="price_line"> | |
| <%# 利用 Rails 提供的 number_to_currency 对价格进行国际化显示 %> | |
| <span class="price"><%= number_to_currency(product.price, unit: "$") %></span> | |
| </div> | |
| </div> | |
| <% end %> | |
| <% end %> | |
| <% end %> | 
