Quick Start Guide

This guide will walk you through the simplest way to add pagination to a Ruby on Rails application.

1. Add will_paginate to your Gemfile

First, add the gem to your Gemfile:

gem 'will_paginate'

Then, run bundle install from your terminal.

2. Paginate Your Query in the Controller

In your controller, use the .paginate method on your ActiveRecord model to fetch a specific page of results. This method replaces a finder like .all.

For example, in app/controllers/posts_controller.rb:

class PostsController < ApplicationController
  def index
    # Fetch paginated posts, 10 per page
    @posts = Post.paginate(page: params[:page], per_page: 10)
  end
end

The page parameter will typically come from the URL query string (e.g., /posts?page=2).

A more modern, chainable syntax using .page is also available:

class PostsController < ApplicationController
  def index
    # The .page method is equivalent and can be chained with other scopes
    @posts = Post.order(:created_at).page(params[:page]).per_page(10)
  end
end

In the corresponding view file, app/views/posts/index.html.erb, use the will_paginate helper to render the pagination links. It's also a good practice to show the user which set of entries are being displayed with page_entries_info.

<h1>Posts</h1>

<div id="posts">
  <% @posts.each do |post| %>
    <%= render post %>
  <% end %>
</div>

<%# Render the pagination links %>
<%= will_paginate @posts %>

<div class="page-info">
  <%# Display a summary, e.g., "Displaying posts 1 - 10 of 55 in total" %>
  <%= page_entries_info @posts %>
</div>

4. Add CSS Styling

That's it! will_paginate will generate the necessary HTML for your pagination controls. You will need to add your own CSS to style the links. You can find example styles on the official project page.