AJAX paginate with rjs and will_paginate

UPDATE: I actually ended up using this solution because the one below was throwing a javascript error on the page.

# helpers/remote_link_renderer.rb
# from http://weblog.redlinesoftware.com/2008/1/30/willpaginate-and-remote-links
class RemoteLinkRenderer < WillPaginate::LinkRenderer
  def page_link_or_span(page, span_class = 'current', text = nil)
    text ||= page.to_s
    if page and page != current_page
      @template.link_to_remote text, :url => url_for(page), :method => :get
    else
      @template.content_tag :span, text, :class => span_class
    end
  end
end
# in the controller
def index
    @images = Image.paginate :all, :per_page => 15, :page => params[:page], :conditions => ['parent_id is null'], :order => 'id DESC'
    respond_to do |format|
      format.html # index.rhtml
      format.xml  { render :xml => @images.to_xml }
      format.js do
        render :update do |page|
          page.replace_html 'images', :partial => "/admin/images/image", :collection => @images
          page.replace_html 'will_paginate', "#{will_paginate @images, :renderer => 'RemoteLinkRenderer'}"
        end
      end
    end
  end
<%= will_paginate @images, :renderer => 'RemoteLinkRenderer' %>

Here is a great tutorial for putting rjs and will_paginate together to ajax paginate things.

However, the new will_paginate uses links differently so you have to add the following to your js block. (Make sure your will_paginate @images is in a div with an id of ‘will_paginate’.

View:

<%= will_paginate @images %>

Addition to js block:

page.replace_html 'will_paginate', "#{will_paginate @images}"

What your js block will look like:

format.js do
   render :update do |page|
      page.replace_html 'images', :partial => "/admin/images/image", :collection => @images
      page.replace_html 'will_paginate', "#{will_paginate @images}"
   end
end

Comments