Update: Click here for will_paginate 2.0
So, Err’s gonna end your troubles by stealing some PHP code. The horror, but as the wise DHH once said:
“When something is too hard it means that you’re not cheating enough.”
Couldn’t agree more. Chowhound was in desperate need of a better pagination solution to help the search bots crawl its 400k topics with ease. I have cool features to build and this is a solved problem, so I go to Google.
30 seconds later, I find Digg-style Pagination. As I mentioned, it’s written in PHP, but there’s something truly statisfying when you take 120 lines of PHP and slim it down to around 40 in Ruby.
The gent even provided some starter CSS so it doesn’t look half-bad from the get-go.
Nice, here’s how it works:app/models/post.rb
class Post < ActiveRecord::Base cattr_reader :per_page @@per_page = 50 end
def index @board = Board.find(params[:id]) @posts, @page = Post.paginate_all_by_board_id(@board.id, :page => params[:page]) endapp/views/posts/index.rhtml
<%= will_paginate(@board.post_count, Post.per_page) %>
Your views will paginate, the code says so.
Grab the plugin here: ./script/plugin install \ svn://errtheblog.com/svn/plugins/will_paginate
Inspect the code here: http://require.errtheblog.com/plugins/browser/will_paginate/
Update: K. Adam Christensen had the right idea moving cruft out of the controller and submitted a sweet addition to the plugin. Chris gave it a little bit of Err love, and I’ve updated the example above to show off how to properly exploit the wonders of this plugin. Ain’t open source grand?
Update #2: With the cleaner code, I skipped the obvious issue of calculating the page number twice. I’ve updated the plugin and the example above with the proper way. Thanks again to Adam.
Update #3: Who else wants on this gravy train? We just added a :per_page option thanks to Dr. Nic. Use it as such:
@posts, @page = Post.paginate_all_by_board_id(@board.id, :page => params[:page], :per_page => 100)
Update #4: This plugin got a whole lot more badass, check out how we’re paginatin’ again for the infos.