仅将主要内容缓存在Rails中 [英] Cache only the main content in rails

查看:50
本文介绍了仅将主要内容缓存在Rails中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Rails 3.1.1和Heroku。



我相信这应该是一个很容易解决的问题,但是我找不到(并容易验证)如何做到这一点。我有一个非常慢的控制器(6秒), Product#show ,有很多 N + 1 以及其他必须解决的问题。 / p>

该网站是一个两栏式网站(主栏右栏),其中 Product#show 的主要内容显示在一列中,而每日产品



我想做的是让<$ Product#show 创建的c $ c>主列将被缓存(从而绕过控制器并赢得6秒钟)。但是,我确实希望右列是动态的(并为每个页面请求加载)。



如果我使用 caches_page:show 会缓存整个网站,包括右列,这使我不得不每天都在缓存中过期才能加载新的日常产品。不是一个好的解决方案。



如果我使用 cache('product-show'+ @ product.slug)做它仅缓存视图(对吗?),仍然必须通过控制器。



那么,我该如何解决?

解决方案

您可以通过如下所示的片段缓存来实现:

  def显示

如果!fragment_exist?( main_content)
@products = Product.all
@users_count = User.count
end

@random_products = Product.order( RANDOM())。limit(10)

end

show.html.erb

 <!-主要内容-> 
<%cache( main_content)做%>
<%= @users_count%>
<%@ products.each做| product | %>
<%= product.name%>
<%end%>
<%end%>

<!-侧面内容->
<%@ random_products.each做%>
<%= product.name%>
<%end%>


Using Rails 3.1.1 and Heroku.

I believe this should be a fairly easy fix but I cannot find (and easily verify) how to do this. I have a very slow controller (6 sec) Product#show, with lots of N+1 and other things I will have to solve.

The website is a two-column website (main-column and right-column) where the main content from Product#show is shown in one column and daily product are shown in the other, including a "Random Product from the Database".

What I want to do is to let the content in main-column that is created by Product#show be cached (and thus bypass the controller and win 6 seconds). I do, however, want the right column to be dynamic (and loaded for each page request).

If I use caches_page :show it will cache the entire website, including the right-column, which makes me have to expire the cache every day in order to be able to load a new Daily Product. Not a good solution.

If I use cache('product-show' + @product.slug) do it only caches the view (right?) and still have to go through the controller.

So, how can I solve this?

解决方案

You can achieve this with fragment caching like below:

def show

  if !fragment_exist?("main_content")
    @products = Product.all
    @users_count = User.count
  end

  @random_products = Product.order("RANDOM()").limit(10)

end

show.html.erb

<!--MAIN CONTENT-->
<% cache("main_content") do %>
    <%= @users_count %>
    <% @products.each do |product| %>
        <%= product.name %>
    <% end %>
<% end %>

<!--SIDE CONTENT-->
<% @random_products.each do %>
    <%= product.name %>  
<% end %>

这篇关于仅将主要内容缓存在Rails中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆