Erik Escobedo
Erik Escobedo

Reputation: 2803

How to cache dynamic fragments in Rails?

Let's say I set a "product" at my controller:

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

And in my /products/show.html.erb I got:

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

I want to do something like this:

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

But, as you can see, the description partial takes a product local variable, generating, of course, a dynamic partial for every specific product.

My question is, how can I use Rail's cache so I only have to generate this partial content the first time an specific product is requested?

Upvotes: 1

Views: 1069

Answers (1)

Ramon Tayag
Ramon Tayag

Reputation: 16084

The trick is giving the cache a specific key, like "product_24_description". That way, each cache would be different:

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

While you're at it, watch this video (and related video) about scaling Rails.

Upvotes: 2

Related Questions