Skip to content

Instantly share code, notes, and snippets.

@saikiranmothe
Created August 14, 2013 13:51
Show Gist options
  • Save saikiranmothe/6231261 to your computer and use it in GitHub Desktop.
Save saikiranmothe/6231261 to your computer and use it in GitHub Desktop.
Pagination with Ajax in Rails Application
Develop pagination with ajax in Rails Application.

Gem Used for pagination


Add gem in Gemfile

gem 'will_paginate', '~> 3.0'

Enable format.js in controller

def index
   # @posts = Post.paginate(:page => params[:page])
    @posts = Post.paginate(:order =>"name ASC" ,:page => params[:page], :per_page => 2)
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
     
## ADD This line to index action ####
      format.js
## ADD This line to index action ####
    end
  end

create a file in views index.js.erb

index.js.erb
---------------

$("#posts").html("<%= escape_javascript(render("posts")) %>");

$('.pagination a').attr('data-remote', 'true');

create a partial in views -- _posts.html.erb

_posts.html.erb
------------

<div class="listing">
<% @posts.each do |post| %>
    <div class="table">
      <span> <%= post.name %> </span>
      <span> <%= post.price %>  </span>
    </div>
<% end %>
</div>
<%= will_paginate @posts %>

Index.html.erb

<h1>posts</h1>
<div id="posts">
  <%= render "posts/posts" %>
</div>
<script>
    $(function(){
        $('.pagination a').attr('data-remote', 'true')
    });
</script>

You can customize the default "per_page" value:

class Post < ActiveRecord::Base
  attr_accessible :name, :price
#You can customize the default "per_page" value:
  self.per_page = 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment