How to Use Pretty URLs with Rails will_paginate Plugin

The will_paginate plugin for Rails uses a key/value assignment like ?page=2, rather than the pretty url formats such as /page/2 … This is because url generation and mapping are handled by the routes.rb file. You’ll need to modify the file so that rails knows what to do with request that match the pattern. Make sure to put the custom (map.connect) route before the normal restful routes (map.resources)

map.connect '/topics/:id/page/:page', :controller => 'topics', :action => 'show'
map.resources :topics

Internally will_paginate uses the url_for method so Rails will now know how to construct your urls in a pretty way. I got most of this info from this discusson http://groups.google.com/group/will_paginate/browse_thread/thread/d0142b512cfca9d5?pli=1

There is nothing wrong leaving the default behavior alone and looking at the ‘ugly’ key/value pairs in the address bar. However, if you take advantage of page caching in rails, you’ll need to do this anyway. Page caching in rails ignore extra parameters, any info before/after the “?” and “&” symbols. There will be no difference from /topics/2?page=1 and /topics/2?page=100 in your cache. And since most likely the content will be very different on these two pages, you’ll need to have pretty urls so that page caching will save topics/2/page/1.html and topics/2/page/100.html as two different resources!

  • http://www.software-click.com Valentin

    Hi Sean! That is awesome. Thanks for sharing!
    I started using this with action caching and followed http://cobaltedge.com/rails-action-caching-with-query-parameters to allow for my sorting params to go through the action cache. Cache paginate and sort together – I love it.
    Val

  • http://www.historicusinc.com Charles Forcey

    Thanks too! This was a big help and much cleaner than writing a custom link renderer. Works for the new 3.0 of will_paginate that is in beta along with Rails 3.

  • http://blog.brijeshshah.com Brijesh Shah

    Hi Sean,

    Thanks for this info … It works for me…

  • http://designers-network.com Gavin Laking

    Since your page comes up in the top ten on Google, I’ll save someone the extra search for Rails 3 rotues:

    One would need something similar to this:

    match ‘/topics/:id/page/:page’ => “topic#show”

    Hope that helps.

    Gav