Rails Kaminari - Ajax pagination

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

Suppose, We are having 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)) }");

This post may help you. Please comment on the same, If you guys have any queries.

Comments

  1. Thanks a lot. Works great. My page was named 'about' so my js file is 'about.js.haml', don't work with the '_' . Are you sure that the name for your js file is '_index.js.haml' ? Regards!

    ReplyDelete
    Replies
    1. Thanks. See, Here I implemented pagination for products. In which, index.haml is the base file where am rendering _products.haml. In order to implement Ajax pagination you should use 2 files. Now read the blog again.

      Delete
  2. anyone out there looking for remote ruby rails jobs should check out http://webwork.io

    ReplyDelete
  3. Thanks for sharing this blog post,Nice written skill selenium Online Course Bangalore

    ReplyDelete

Post a Comment

Popular posts from this blog

Rails 4, MySQL, and Emoji (Mysql2::Error: Incorrect string value: '\xF0\x9F\x8C\x9D')