views:

283

answers:

3

I am looking for a suggestion on the best way of having an end user from a Rails application's view files set the sort order of a result set returned by a model's "find" method. In other words I would like a user to be able to choose their sort order from a selection list.

Initially, I thought I could just put the string that I would put in the :order parameter, but that seems like a bad idea from a security point of view.

I suppose I could always use a switch based off values from a selection list, but that seems a bit bulky.

Thanks for looking.

+3  A: 

I would use AR::Base#column_names to sanitise the input. Something like:

@models = Model.find(:all, :order => params[:sort].select({|name| Model.column_names.include? (name) } ).join(',') )

You can extend this, with a little pre-processing, to vary whether you want to sort ascending or descending with each key. Hope this helps!

Marcel Guzman
Nifty, thank you :)
jklina
+2  A: 

This might be outside of what you're looking for, but lately, I've been relying on javascript to take care of the subsequent sorting for me. A good table sorter for prototype is Tablekit (http://www.millstream.com.au/view/code/tablekit), it's unobtrusive, fast, and easy to use. It also includes niceties like editing in place and column resizing.

Dan McNevin
A: 

something rails could copy from cakephp scaffold (paginator sorter on index() in cakephp)

Ed