Thursday, March 17, 2016

Pagination Rails using Kaminari gem

When we work with just couple of records, it's easy to simply list them all on the index page. But, what happens when we have more than two, let's say 100 records? What if we have 1000? How about 1 million? If we try to list all records from the database on a website at once, not only it will be a lot of load on the database, download will take much longer time, but it's likely that user's browser will crash.

Step 1: Add Kaminari and Bundle Gems

First, add kaminari to the Gemfile


gem 'kaminari'

gem 'kaminari-bootstrap'

because we use bootstrap for style, so kaminari-bootstrap are nicely styled.

$ bundle install



as example:
we use Product If you are working with posts, go to product_controller.rb and replace def index like this:
def index
  # @products = Product.all we will replace this old code - you can delete this line

  @products = Product.order('created_at DESC').page(params[:page]).per(15)
end

Step 2: Add navigation button in view

Add <%= paginate(@products) %>
<p id="notice"><%= notice %></p>



<h1>Listing Products</h1>



<table class="table table-striped"> 

  <thead>

    <tr>

      <th>Code</th>

      <th>Name</th>

      <th>Price</th>

      <th>User</th>

      <th colspan="3"></th>

    </tr>

  </thead>



  <tbody>

    <% @products.each do |product| %>

    <tr>

      <td><%= product.code %></td>

      <td><%= product.name %></td>

      <td><%= product.price %></td>

      <td><%= product.user %></td>

      <td><%= link_to 'Show', product %></td>

      <td><%= link_to 'Edit', edit_product_path(product) %></td>

      <td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>

    </tr>

    <% end %>

  </tbody>

</table>

<%= paginate(@products) %>

<br>



<%= link_to 'New Product', new_product_path %>




Reference :
peoplecancode

Bagikan

Jangan lewatkan

Pagination Rails using Kaminari gem
4/ 5
Oleh