hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

A Pagination Helper For Rails #

by why in inspect

Sam Stephenson’s PaginationHelper for Rails interacts with ActiveRecord to ensure only a single page of data is loaded from the database and handles links to the other hidden pages. It’s a helper script that I’ve been using everywhere.

Helpers are mixins which add methods to the Rails controller and templates. Install a helper by copying it into /app/helpers/ in your Rails application. Here’s an updated PaginationHelper I’ve updated for Rails 0.90: pagination_helper.rb.

Load the helper at the beginning of a controller like this:

 class BlogPostsController < ApplicationController
   helper :pagination
   include PaginationHelper
 end

Not all helpers require the include statement. We’ll be using the Paginator class inside the helper, so it’s necessary in this case.

Now, you’ll need to use the Paginator in tandem with ActiveRecord#find to grab a single page of data for display:

 @pages = Paginator.new self, BlogPosts.count, 30, @params['page'].to_i
 @posts = BlogPosts.find nil, "post_time DESC", @pages.current.to_sql

My remix of the PaginationHelper (linked above) also features a simple method for generating a window of page links. The Paginator#window_links method accepts your template’s view object and a window size.

I’ve stored my paginator links in a partial called /app/views/partial/_pager.rb:

 <div id="counter">
   Displaying <%= @pages.current.first_item %>
   - <%= @pages.current.last_item %>
   of <%= @pages.item_count %> &nbsp; &nbsp;

   <%= link_to( h('< Previous'), @pages.current.previous.to_link ) + " | " if
     @pages.current.previous %>
   <%= @pages.window_links( self, 4 ) %>
   <%= " | " + link_to( h('Next >'), @pages.current.next.to_link ) if
     @pages.current.next %>
 </div>
said on
The helper :paginator is a pretty alternative to manually doing the include. You only need one of them, though. So throw away that include statement and live happily ever after ;)
said on
I know it's supposed to work like that, David. But if I don't use include, I get an exception thrown: uninitialized constant ThreadsController::Paginator. Anyway, add_template_helper only mixes the module into the template class, right? I would need to manually mix into the controller class in order to use the helper there.
said on
You don't need the casting in @params['page'].to_i because as written, the paginator helper will cast the page params for you.
said on

asasa

said on

for the test

said on

test

said on

I want to paginate a search result, that join with other object. The current paginate method suppose to support the whole model colection. Anyoe could point me a solution for this

said on

Liked that

said on

live happily ever after :)

said on

living happily ever after :)

said on

:))

said on

nice!

said on

nice!

Comments are closed for this entry.