Ajay Sharma
Ajay Sharma

Reputation: 31

pagination with ajax in rails 2.3.8

Can anyone suggest me how to use will_paginate with ajax in rails 2.3.8 what should i make changes in following code line in ClientController

def index

    @clients = Client.paginate(:per_page => 5, :page => params[:page])
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @clients }
    end

end

and in index view file

<%= will_paginate @clients %>

Upvotes: 0

Views: 589

Answers (1)

Nick
Nick

Reputation: 2413

will_paginate doesn't have native AJAX support but does offer switching out the link renders. Add the following class to remote_link_renderer.rb in RAILS_ROOT/lib to enable a rendered view of a link suitable for AJAX callbacks:

class RemoteLinkRenderer < WillPaginate::LinkRenderer
 def prepare(collection, options, template)    
   @remote = options.delete(:remote) || {}
   super
 end
protected
 def page_link(page, text, attributes = {})
   @template.link_to_remote(text, {:url => url_for(page), :method => :get}.merge(@remote))
   #replace :method => :post if you need POST action
 end
end

Use this in your views to render pagination links (customize as needed):

<%= will_paginate(@results, :params => {:controller => :mycontroller, :action => :search, :query => h(@query)}, :renderer => RemoteLinkRenderer, :page_links => false) %>

The controller gets a little more tricky since you need to replace the view that rendered those pagination links and results. I used something like this:

  if request.xhr? or request.post?
    if params[:page]
      render :update do |page|
        page.replace_html :search_results, :partial => 'mycontroller/search_results', :layout => false
      end
    else
      render :partial => 'mycontroller/search_results'
    end
  else
    # Render some normal content here
  end

Upvotes: 1

Related Questions