Coding Tidbits

Cube Root is an exclusive Ruby on Rails Consultancy. Find our programming ramblings here.

Ajax Pagination In Rails

In this blog post we will see how to apply rails pagination on Ajax. Here, I am doing pagination using kaminari.

1.Add following gem in your Gemfile.

gem kaminari

2.bundle install

3.Open your controller file in which you want to apply pagination.

def index
  @products =[:page]).per(10)
        respond_to do |format|

4.In view file index.html.haml.

      = render :partial => '/products/product', :locals => {:products => @products}

      = paginate @products, :remote => true

5.Add following code in _product.html.haml file.

  @products.each do |product|

6.Create new file _index.js.haml and add following code in it.

$('#products').html('<%= escape_javascript render(:partial => '/products/product', :locals => {:products => @products}) %>');
$('#paginator').html('<%= escape_javascript(paginate(@products, :remote => true).to_s) %>');     

And it's done! pagination works with ajax.