Series: Plug-in arsenal - Paginating Find

February 15th, 2008

Books and recordsets!

Oh, pagination. How you have been tormented over the years in the Rails community. For those of you who have no idea what the devil pagination is, run a search on Google and take a look at near the bottom of the page – You should see “previous” and “next” links, alongside numbers of pages with which to jump to. That’s pagination!

I believe the majority of current opinion on paginating through records is to avoid using the Rails 1.0 built-in Pagination class. In Rails 2.0, it’s been removed and requires the install of an additional plug-in to receive the previous functionality. Cue Paginating Find, a plug-in written by Alex Wolfe of Carboard Rocket. I first learned of Paginating Find via Ilya Grigorik’s blog, as he had written some Helpers & View Partials to support it. Let’s jump in, shall we?

You can install Paginating Find here:
1
ruby script/plugin install http://svn.cardboardrocket.com/paginating_find

Paginating Find overrides the default ActiveRecord::find method, and allows a new set of options dubbed :page to accompany the familiar :conditions, :order, etc. We’ll use a Bulletin model for our example:

bulletin.rb (Model)

1
2
3
4
5
6
7
def self.find_all_using_pagination( options = {} )
  return self.find( :all,
    :page => { 
      :size => options[:number_of_records],
      :current => options[:current_page]
    } )
end

These options are typically provided by GET variables passed through the URL string to the controller. The new :page option requirs two vars, :size & :current. Use :size to dictate how many Bulletin’s should be pulled from the database per page, and :current to state which page we’re currently viewing. For example, if :current is set to 2, and :size is at 10, we would receive Bulletin’s 11-21.

The best part about Paginating Find is that it works transparently. If you don’t provide the :page option in the find() call, Rails will enact a regular find() call and ignore the fact that Paginating Find is even installed.

Further readings:

Sorry, comments are closed for this article.