Reputation: 3417
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.
Upvotes: 6
Views: 566
Reputation: 1752
something rails could copy from cakephp scaffold (paginator sorter on index() in cakephp)
Upvotes: 0
Reputation: 22336
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.
Upvotes: 2
Reputation: 1672
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!
Upvotes: 4