Pagination

Posted . Visible to the public.

Update Gemfile

  1. Add pagination gems to general section at the top of the Gemfile.
    source 'https://rubygems.org'

    gem 'rails', '3.2.12'
    gem 'bootstrap-sass', '2.3.0.1'
    gem 'will_paginate', '3.0.4'
    gem 'bootstrap-will_paginate', '0.0.9'
      *
      *
  1. Run bundle install
    Note: You may have to run bundle update first if this is the first time you've used pagination.

Add pagination to the ApplicationController subclass

class UsersController < ApplicationController
    *
    *
  def index
    @users = User.paginate(page: params[:page])
  end
    *
    *
end

Add pagination to the view

~/rails_projects/sample_app/app/views/users/index.html.erb

<% provide(:title, 'All users') %>
<h1>All users</h1>

<%= will_paginate %>

<ul class="users">
  <%= render @users %>
</ul>

<%= will_paginate %>

Configure the number of items on a page at the global level

  1. Create a new file: <<app_home>>/config/initializers/will_paginate.rb

  2. Enter the following:

    # Set global value for pagination number of items per page
    # This can be overridden in a specific model class
    WillPaginate.per_page = <<number of items>>

Configure the number of items on a page at the model level

class User < ActiveRecord::Base

  # set the number of users to display on each page when paginated
  # this will override the global value
  self.per_page = 10
    *
    *
  end

Pagination Sample

Here's a sample of a user index page with pagination. For more info, visit the github site for the will_paginate gem at the link below.

Profile picture of jarsen
jarsen
Last edit
Posted by jarsen to Ruby on Rails (2013-03-14 17:01)