AJAX Pagination and Sorting in Ruby On Rails

I recently decided the account section of a Rails application I’m working on will be completely AJAX. Every link the user would click on would just replace a section of the account page giving them the impression that they’ve never left their account section because the URL isn’t changing. However, I needed to do pagination and sorting for lists of different things. So hunting on Google I went.

I first came across this article over at Rails on the Run about how to do it with will_paginate, prototype, and low pro. I mucked around with it for about 30 minutes and definitely had some struggles, so I went back to Google. I eventually came across this article at Redline Software’s Weblog about an easier way to do it with will_paginate. The nuts and bolts of it is you can use a helper class to write your pagination links for you very easily (I won’t steal their code and post it here. Check out the link to grab it.)!

But I’m not done yet. Remember, I also need to be able to sort my lists of data. So I ran with the same idea presented by Redline Software and came up with this way to write out the anchor tags for my sort links:

def sort_remote_url(text, value)
    value += "_reverse" if params[:sort] == value
    @template.link_to_remote text, {:url => params.merge(:sort => value)}
end

What sort_remote_url does is take in the text for the link and the value of the sort parameter. When you click on the sort link, it works just like the pagination and updates the current view.

Leave a Reply

Your email address will not be published. Required fields are marked *