Saturday, January 26, 2008

Pagination

When displaying a list of information to the user, it's always handy to separate it into several pages if your list gets too long. This is a very common task, but also a very redundant and mundane task.

The logic to figure out how to display the page links is rather repetitive:

<Prev 1 2 ... 99 100 Next>

Instead of wasting time writing and rewriting this, wouldn't it be a better use of time working on something else? Well, there's a plugin that makes your life easy! It's called will_paginate.

will_paginate gives a wrapper around the find functions, allowing you to give the page number you want, and it returns to you just those objects that will be displayed on the page. Furthermore, with one simple function call, the nice page links will be displayed for you properly! Check out the will_paginate page for a quick example.

The only down-side I found to this plugin was that it didn't support AJAX. I hope that in one of the future releases they'll add AJAX support. In the meantime, I added one myself called will_remote_paginate. It merges will_paginate and the usual remote calls together like so:

<%= will_remote paginate @products, :url => list_products_path, :method => :get %>

If your interested in seeing what I did, give me a shout and I'll post it up. It's not the best solution in the world, but at least it works for me!


W

No comments: