Hi! Thanks for visiting my blog. If you've received any value from my content would you mind supporting my new startup by downloading our browser add-on? It's called PriceBlink and makes online shopping a breeze. You can watch it in action here and download it for Chrome, Firefox, IE, or Safari by going to PriceBlink.com. Thank you and I hope you enjoy!

Paging with Ruby on Rails

Apr 01

While the whole concept behind Ruby on Rails is don’t repeat yourself (DRY), sometimes I think it’s more like don’t write code  (DWC).  I speak, in this instance, of paging through data using Ruby on Rails.  I also say this coming from a ColdFusion background where you normally had to roll your own paging logic.  It would be something to the effect of determining the number of results to display to the user, calculating the number of pages, etc.  Not that this was an extremely difficult task, but it could take a decent of code and it’s logic that needs to be managed within the application.

Rails allows this to be done with no more than a single line of code (possibly two depending on your approach) within the view template.  If you’ve looked through any scaffolding code then you may have noticed the paging object created in the controller.  Let’s say you have a person object then your list method will look like the following:

def list
@person_pages, @people = paginate :people, :per_page => 10
end

Notice the paginator object (@person_pages) as well as the people object that stores the list of people for a given page.  In the view the “Next” and “Previous” links are displayed using the following code:

[%= link_to 'Previous page', { :page => @person_pages.current.previous } if @person_pages.current.previous %]
[%= link_to 'Next page', { :page => @person_pages.current.next } if @person_pages.current.next %] 

Pretty straightforward and very little logic for the developer to maintain.  When the “Next” and “Previous” links are clicked a url parameter named page is passed to the controller.  This tells the paginator which group of people to return.  So displaying “Next” and “Previous” seems manageable for up to 30 results, but what if there are thousands of results?  Have no fear, that’s what the pagination_links method is for.  Its usage is very simple:

[&= pagination_links(@person_pages) %]

This creates a numered paging system that’s very simple to use.  It’s even smart enough to display only a few pages of links if there are hundreds or even thousands of results.  The format will look something like 1 2 3 …. 13 14.  The pagination helper built into Rails is a much needed piece of functionality that has saved me hours of development time.  If you’re dealing with any sort of data intensive application then I highly recommend looking into the Ruby on Rails PaginationHelper.

Leave a Reply