Restful Pagination in Rails

Labels: , ,

Have you ever tried to cache your paginated lists? Sadly, vanilla Rails wont help much as they ignore the url query parameters when caching and hence the page=x value is not honored and Rails caching (action or page caching) will simply stick to the first page rendered for all requests.

One might come with a solution that overrides the cache key generation to incorporate the query string, which will work, but will result in very long and ugly hash keys.

Luckily there is a better approach, if you simply defined routs for pages (for the paginated resources) and name them page parameter with the same name you give it in the paginator then Rails will pick up the route when creating paginated links.

In your routes.rb
map.resources    :users
map.paged_users '/users/pages/:page'
map.formatted_paged_users '/users/pages/:page.:format'

once the above routes are in place, all you need is to make sure your paginators are using 'page' as the page parameter name and you will see the pagination links created like this:
/users/pages/1
/users/pages/2

Don't forget the formatted route to support pagination with various formats so you can use routes like:
/users/pages/1.xml

These urls are very cache friendly and adhere to REST much more than the default parameters based ones.

Happy caching (with pagination)

Comments (4)

Excellent article. This is exactly what I was looking for and you provided such an elegant approach. Thanks for sharing!

This doesn't work, it returns the error: "Illegal route: the :controller must be specified!"

This was for an old Rails version (1.2.x). You can try specifying the controller (and may be the action as well) in your route

Making hero gold
is the old question : Honestly there is no fast way to make lots of hero online gold. Sadly enough a lot of the people that all of a sudden come to with millions of hero online moneyalmost overnight probably duped . Although there are a lot of ways to make lots of hero money here I will tell you all of the ways that I know and what I do to buy hero gold.