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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With