A Pagination Helper For Rails #
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 %> <%= 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>
David Heinemeier Hansson
why
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.Lucas Carlson
ashish
asasa
sorry
for the test
so
test
Hanoi@fpt
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
Riax
Liked that
nice one
live happily ever after :)
nice one
living happily ever after :)
:))
:))
me
nice!
me
nice!
Comments are closed for this entry.