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>
<script>
$(document).ready(function() {
$('.pagination a').attr('data-remote', 'true');
});</script>



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|
format.html
format.js
end
end



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.

7 comments:

paxer said...

Thanks mate ! Exactly what i was looking for !

Anonymous said...

Great post! Very helpful :)

Anonymous said...

Great post! Very helpful :)

Unknown said...

it is working fine, but i couldn't update the paginate div

Unknown said...

it is working fine, but i couldn't update the paginate div

Unknown said...

Anyone managed to get the pagination div updated using this method? Ajax works fine but I can't update the links.

Unknown said...

Here's the fix for the not updated links: http://stackoverflow.com/a/7422878/788754