Ruby on Rails
HowToCachePagesWithParameters

Let’s say you have an action, band_info, that shows information about a particular band. The id of the band is passed to the action so that the url looks like

app/band_info?band_id=123
. Caching this action with caches_page in the controller results in the cached page
app/band_info.html
, which loses all info about the parameter. This defeats the point of caching as the database query must be rerun on each successive request for band_id 123.

But the page is prime for caching, so there must be a way to cache this.

Well, not quite, but there is a work-around. In order cache this page, you’re going to have to stick a custom route between the request and the controller.

For example, the default request might look like this:

/image/gradient/?size=100&color1=FF0&color2=00F

In order to cache it, we edits routes.rb and add a line like this:

map.gradient 'image/gradient/:size/:color1/:color2',
    :controller => 'image', 
    :action => 'gradient'

The gradient page must now be requested as this:

/image/gradient/100/FF0/00F/

The page will now be cached like any other (default in /public/), with a directory structure that mirrors the custom route.

This also has the nice side-effect of creating a named route which will automatically create the application helper:

gradient_url(:size => 100, :color1 => 'FF0', :color2 => '00F')

... which you’ll likely need as you rewrite the urls in your app to accommodate this hack.

PS : This is not a hack. This is way to do it :)