Wednesday, 24 November 2010

will_paginate and ajax in rails 3

After googling and stackoverflowing around I couldn't find anything that explicitly said how do to this.

I have a page that has 'pagable' areas on it, and want to load these using ajax. And I am in rails 3!

I found it actually was quite easy and only needed a few lines of code.

1 - In the page view (users/show.html.erb)
To enable the data-remote attribute on will_paginate's links

<div id="queue"><%= render :partial => 'queue' %></div>
$(document).ready(function() {
$('.pagination a').attr('data-remote', 'true');

2 - In the controller (users_controller.rb)
To allow a js response

def show
@user = User.find(params[:id])
@queue_items = @user.queue_items.with_state(:pending).paginate(:page => params[:queue_page] || 1, :per_page => 1)
respond_to do |format|

3 - A show.js.erb template
You need the second line to reapply the data-remote to the new links
$('#queue').html('<%=escape_javascript render :partial => "queue" %>');
$('.pagination a').attr('data-remote', 'true');

That's it! Your new dataset should load into the 'queue' div.