Posts Tagged ‘will_paginate’

ajaxify wil_paginate with lowpro

October 13, 2008

Here’s the case
– I am in rails;
– I am in a search page that displays two types of results: videos and profiles;
– Each are paginated thanks to will_paginate;
– I want to use videos and profiles with ajax, not to modify the rest of the web page.

Solution
First of all, I include the lowpro library in my layout to think unobstrusive about javascript:

<%= javascript_include_tag 'lowpro' %>

Here is my controller:

class SearchController <  ApplicationController
  def index
    @profiles = Profile.search params[:query] :page => (params[:profile_page] || 1)
    @videos = Video.search params[:query], :page => (params[:video_page] || 1)

    respond_to do |format|
      format.html
      format.js do
        render :update do |page|
          if params[:profile_page]
            page.replace_html 'profiles', :partial => "profiles"
          elsif params[:video_page]
            page.replace_html 'videos', :partial => "videos"
          end
        end
      end
    end
  end
end

Here is my view:

<div id="profiles">
	<%= render(:partial => 'profiles') %>
</div>
<div id="videos">
	<%= render(:partial => 'videos') %>
</div>
<script type="text/javascript">
//<![CDATA[
Event.addBehavior.reassignAfterAjax = true;
Event.addBehavior({
	'#profiles_pagination a' : Remote.Link
})
Event.addBehavior({
	'#videos_pagination a' : Remote.Link
})
//]]>
</script>

And last, one of my partial:

<h3>Profiles</h3>
<% for profile in @profiles -%>
<%= link_to profile.name, show_profile_path(profile.name) %>
<% end %>
<%= will_paginate @profiles, :param_name => 'profile_page', :id => true %>

Done
But… don’t hesitate to comment, question or suggest improvements.

Thanks,
Guillaume