Rails Kaminari – Ajax pagination

Here is a simple way to implement AJAX pagination using the Kaminari gem.

Suppose, we have a product model with fields id and name.

So, in the ProductsController,

def index
  @products =  Product.all.page(params[:page]).per(params[:per])
   respond_to do |format|
      format.js
      format.html
    end
end

in view file index.html.haml

  #products
    = render ‘products’
  #paginator
    = paginate @products, :remote => true

And create _products.html.haml(this will be rendered from index) with content
%table
    @products.each do |product|
     %tr
       %td= product.name

Finally, we have to create one more  file _index.js.haml with content

$(‘#products’).html(“#{escape_javascript(render ‘products’)}”);
$(‘#paginator’).html(“#{escape_javascript(paginate(@products, :remote => true)) }”);

Hope this post helps you Ruby freaks. Please post your comments in case you have any queries.

Jyothish Kumar is a Consultant Developer at Compassites Software Solutions Private Limited. His areas of work includes Ruby On Rails and Web technologies. Prior to Compassites, he worked at Mobme Wireless Solutions PrivateLimited. He is an active contributor on websites that offer technical help. Jyothish also has a technology blog of his own. He loves working on Ruby on Rails related projects. He hails from God’s own country (Kerala).

Leave a comment