我正在玩片段缓存,我已经阅读了指南并观看了 railscast。
我正在尝试对基本的显示操作进行一些片段缓存:
控制器:
class PostsController < ApplicationController
before_action :set_post, only: [:show]
def show
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.friendly.find(params[:id])
# @post = Post.find(params[:id])
end
end
看法:
<% cache @post do %>
<h1><%= @post.title %></h1>
<%= @post.content %>
<% end %>
问题:虽然片段是构建和读取的(见下面的日志),但数据库仍然被命中。这是正常行为吗?
我怀疑在读取缓存之前触发查询之前的操作过滤器。
我怀疑友好的 id 系统,但查询也发生在经典的 find 中。
我应该如何缓存它以避免查询?
日志:
Started GET "/articles/article-3" for 127.0.0.1 at 2014-08-27 10:05:14 -0400
Processing by PostsController#show as HTML
Parameters: {"id"=>"article-3"}
Post Load (1.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."slug" = 'article-3' ORDER BY "posts"."id" ASC LIMIT 1
Cache digest for app/views/posts/show.html.erb: 18a5c19e6efef2fd1ac4711102048e1c
Read fragment views/posts/3-20140730194235000000000/18a5c19e6efef2fd1ac4711102048e1c (0.5ms)
Rendered posts/show.html.erb within layouts/application (4.8ms)