Best practice for fragment caching a dynamic listing?


#1

Hi,

I’m new to fragment caching, and was wondering the best way to do it for
a dynamically generated page. I have been working off of the “Agile Web
Development with Rails” book, but it’s rather brief on fragment caching.

For example, suppose you have a list of manufacturers and each of which
has many products. Here is how I would implement the caching, but I’m
not clear if it will work, or if there’s a cleaner, less clunky of doing
it:

Product Controller:
def list
@mid = params[:manufacturer_id]

if @mid.nil?
@mid = “all”
unless read_fragment(:action => ‘list’, :mid => “all”)
@products = Product.find(:all)
end
else
unless read_fragment(;action => ‘list’, :mid => @mid.to_s)
@products = Product.find_by_manufacturer_id(@mid)
end
end

end

View (list.rhtml)
<% cache(:action =>‘list’, :mid => @mid) do %>

    <% for p in @products %>
  • <%= p.name %>
  • <% end %>
<% end >

Any suggestions or advice on a better way to to go about doing this
would be much appreciated. Thanks.


#2

Jay,

I’m fairly new to Rails too, but the code looks fine. There are no doubt
more Ruby ways of writing it.

One thing. Doesn’t the cache need to be expired when a manufacture
updates?

Xin


#3

Xin Z. wrote:

Jay,

I’m fairly new to Rails too, but the code looks fine. There are no doubt
more Ruby ways of writing it.

One thing. Doesn’t the cache need to be expired when a manufacture
updates?

Xin

Yes, I didn’t include the code for putting in sweepers to expire the
cache when the manufacturer/product is updated. Does anyone have any
recommendations for production-ready plugins that make this simpler?
I’ve been bouncing around the various plugin sites, and haven’t found
one that seems to make this as easy as it should be.

One promising one is this one, but I don’t think I would call it
production-ready, as it looks like it was released yesterday:

http://blog.overlay.tv/articles/2007/06/16/intelligent_fragment_cache