Skip to content

Instantly share code, notes, and snippets.

@serabakpak
Last active October 13, 2016 17:05
Show Gist options
  • Save serabakpak/048703636672ce18014a6221947fa379 to your computer and use it in GitHub Desktop.
Save serabakpak/048703636672ce18014a6221947fa379 to your computer and use it in GitHub Desktop.
Adding Pagination to your Rails app using kaminari

Adding Pagination to your Rails app using kaminari

What it is

From their GitHub page: "A Scope & Engine based, clean, powerful, customizable and sophisticated paginator for modern web app frameworks and ORMs"

Why it's awesome

  • Easy to use
  • No configuration required
  • Don't have to define anything in your models or helpers.

To get started

Add this line to your Gemfile

gem 'kaminari'

Then don't forget to run bundle in terminal!

Controller

In your controller, call the .page method on your model.

# creatures_controller.rb

class CreaturesController < ApplicationController

  def index
    @creatures = Creature.page(params[:page])  
  end

By default, kaminari loads 25 records per page, but you could change that by adding .per(number) to the previous line of code.

# creatures_controller.rb

class CreaturesController < ApplicationController

  def index
    @creatures = Creature.page(params[:page]).per(5)  
  end

View

Then enter this paginate helper wherever you want the paginated pages to show in your view.

# app/views/creatures/index.html.erb

  <%= paginate @creatures %>

Pagination Example

Query (In Rails Console)

To fetch the 3rd page of users use the .page query method

Creature.page(3)
  • Pagination starts on page 1 not 0.

For more, GitHub Query Basics

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment