【问题标题】:How to cache dynamic fragments in Rails?如何在 Rails 中缓存动态片段?
【发布时间】:2011-08-16 02:54:59
【问题描述】:

假设我在控制器上设置了一个“产品”:

# products_controller.rb
def show
  @product = Product.find(params[:id])
end

在我的/products/show.html.erb 中,我得到了:

<%= render :partial => 'products/description', :locals => { :product => @product } %>

我想做这样的事情:

<% cache do %>
  <%= render :partial => 'products/description', :locals => { :product => @product } %>
<% end %>

但是,如您所见,description 部分采用 product 局部变量,当然会为每个特定产品生成动态部分。

我的问题是,我怎样才能使用 Rail 的缓存,这样我只需要在第一次请求特定产品时生成这个部分内容?

【问题讨论】:

    标签: ruby-on-rails caching


    【解决方案1】:

    诀窍是给缓存一个特定的键,比如“product_24_description”。这样一来,每个缓存都会有所不同:

    cache "#{dom_id product}_description" do
      ...
    end
    

    在此过程中,请观看有关 scaling Rails 的视频(和相关视频)。

    【讨论】:

      猜你喜欢
      • 2012-06-02
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      相关资源
      最近更新 更多