views:

1847

answers:

2

Any tips on how to implement sorting and pagination on a resource in a Rails application and still keeping it RESTful?

How do I map the parameters for page number and sort field in a clean way? (I am currently using map.resources :x for every resource in my app)

Any other performace issues involved that I should know about? (eg. caching)

Thanks in advance.

EDIT I reformulated the question into a more generic one, hoping that I will get more answers. I'm going to vote to close this one since it is no longer relevant. Thanks for the answers insane-dreamer and vrish88.

+1  A: 

I would recommend you take a look at this article:

http://dev.nozav.org/rails_ajax_table.html

http://dev.nozav.org/ajaxtable/ (this is the demo application)

I have used the same basic code in one of my applications. I didn't use the AJAX implementation that they describe but I used the sorting helpers that they mention and then I structured my view to enable sorting. In the sorting helpers you'll just want to take out the ajax related stuff. Mine end up looking like this:

def sort_link_helper(text, param)
  key = param
  key += "_reverse" if params[:sort] == param
  parameters = params.merge({:sort => key, :page => params[:page], :action => controller.action_name })
  link_to(text, url_for(parameters))
end

def sort_td_class_helper(param)
  result = 'class="sortup"' if params[:sort] == param
  result = 'class="sortdown"' if params[:sort] == param + "_reverse"
  return result
end

The best part about this implementation is that is RESTful, DRY and easy to use!

vrish88
andi
Hmmm, well I don't really know to much about caching but couldn't you just store the results of the sql query and then sort the results from the cache? Also, I don't know of any other way to store the page and sort variables that would make sense... but I am open to suggestions
vrish88
"Note: Page caching ignores all parameters, so /products/list?page=1 will be written out to the filesystem as /products/list.html and if someone requests /products/list?page=2, they will be returned the same result as page=1. Be careful when page caching GET parameters in the URL!"
andi
I got that from here: http://guides.rubyonrails.org/caching_with_rails.html
andi
Check this out: http://www.railsenvy.com/2007/2/28/rails-caching-tutorial#pagination. It gets rid of the pagination problem but not the sorting.
vrish88
+4  A: 

Have you tried will_paginate? Is there some reason it doesn't meet your specific needs? (http://github.com/mislav/will_paginate/tree/master)

insane.dreamer
I already use the will_paginate plugin. I was hoping for more answers regarding the REST part. I think I will reformulate the question, removing the 'rails specific' parts.
andi