Thursday, 16 April 2015

Pagination With Ajax Using Will Paginate in Ruby on Rails



step1: I have and index page. TO display all records.

controller method:
    def index
      @products = Product.paginate(:order =>"name ASC" ,:page => params[:page], :per_page => 14)
      respond_to do |format|
        format.html # index.html.erb
        format.json { render json: @products }
        format.js
      end
    end


step2: i have a dorp down with type1 ans type2 categories.
index.html.erb

<h1>Products</h1>
<%= select_tag :type, options_for_select([["type1",1],["type2",2]]), { :prompt => 'Select Category', :class => 'form-control', :id =>"type", :style => "width: 24%;margin-bottom: 7px;"} %>
<div id="products">
 <%= render "products/products" %>
</div>

<script>
$( document ).ready(function() {
    $("#type").change(function() {
        var type = $('select#type :selected').val();
        $.ajax({
            url: '/admin/index/'+type,
                dataType: "script"
        });
    });
    $(function(){
           $('.pagination a').attr('data-remote', 'true')
    });
});
</script>

step 3:
index.js.erb

jQuery('#products').html(" 'products/products' )%>");
$('.pagination a').attr('data-remote', 'true');

step 4:
_products.html.erb
<div class="listing">
      <% @products.each do |product| %>
        <div>
     <span> <%= product.title %> </span>
           <span> <%= product.price %>  </span>
        </div>
     <% end %>
</div>
<%= will_paginate @products %>


Thats all. ajax based pagination is done....

No comments:

Post a Comment