Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Way of Having End User Specify Sort Order in Rails

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.

like image 331
jklina Avatar asked Apr 06 '09 22:04

jklina


1 Answers

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!

like image 67
Marcel Guzman Avatar answered Sep 23 '22 18:09

Marcel Guzman