Skip to content

Adding AJAX to will_paginate

Ronald Chan edited this page Feb 23, 2012 · 11 revisions

This is the recommended way to add AJAX to will_paginate, and assumes that you have already installed AJAX Pagination. Some steps could be skipped, but would also miss some highly recommended features.

Suppose your view index.html.erb contains:

<%= will_paginate @objects %>
<% objects.each do |object| %>
  ...
<% end %>

Move that content, including the will_paginate tag to a partial called _page.html.erb, and set params[:pagination] to nil as shown. Then wrap the rest of the content using the ajax_pagination_loadzone tag. Your partial will contain:

<%= will_paginate @objects, :params => { :pagination => nil } %>
<%= ajax_pagination_loadzone do %>
  <% objects.each do |object| %>
    ...
  <% end %>
<% end %>

In your index.html.erb, instead of the content which you moved to the partial, use the following code:

<%= ajax_pagination %>

Finally in your controller action, add a line calling ajax_pagination to your respond_to block as shown:

Class ObjectsController < ApplicationController
  def index
    ...
    respond_to do |format|
      format.html # index.html.erb
      ajax_pagination(format)
    end
  end

  ...

end

And you are done. Here is an example of it in action:

AJAX Pagination applied to will_paginate

For more advanced guides see:

  • Use AJAX Pagination a 2nd time in will_paginate in the same controller (Not written yet, read Usage in the readme)