Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails在基本show操作上使用片段缓存避免查询_Ruby On Rails_Caching_Ruby On Rails 4_Fragment Caching - Fatal编程技术网

Ruby on rails Rails在基本show操作上使用片段缓存避免查询

Ruby on rails Rails在基本show操作上使用片段缓存避免查询,ruby-on-rails,caching,ruby-on-rails-4,fragment-caching,Ruby On Rails,Caching,Ruby On Rails 4,Fragment Caching,我正在玩碎片缓存,我已经阅读了指南并观看了railscast 我正在尝试对一个基本的show action进行一些片段缓存: 控制器: class PostsController < ApplicationController before_action :set_post, only: [:show] def show end private # Use callbacks to share common setup or constraints betwee

我正在玩碎片缓存,我已经阅读了指南并观看了railscast

我正在尝试对一个基本的show action进行一些片段缓存:

控制器:

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 %>

除非您的应用程序只有一个post,否则我真的不认为您会希望缓存第一个调用-片段缓存将缓存给定的post,但它仍然需要知道正在访问哪个post


如果你缓存了这篇文章,那么每次你加载post#show页面时,不管你请求什么帖子,你都会看到一篇帖子——缓存的帖子

我明白了,我们需要知道我们要访问哪个帖子才能获得正确的缓存。但实际上,如果我使用模型缓存(Rails.cache.fetch(){Myquery})而不是片段缓存,我可以检查缓存是否存在,并仅在不存在时触发查询。但这比片段缓存和自动过期更复杂。我读到的每一篇关于片段缓存的文章都使用这种例子来描述正在缓存的对象,但没有提到查询。您的目的是告诉我们,查询是不可避免的,但是缓存对于获得渲染时间仍然是有用的?可能这取决于。您的db调用只有1.2毫秒,您的视图需要4.8毫秒。我想我不会为这样的缓存而烦恼,但可能您正在使用一个简化的示例。数据库调用不会改变(除非需要更多)-视图可能会变得更复杂,在这种情况下,您可能会发现通过缓存节省的时间是值得的。
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)