Avoiding SQL Injection in :order?

Danny Burkes wrote:

How about calling ActiveRecord#sanitize_sql directly?

-- Posted via http://www.ruby-forum.com/.

My solution to this is to have the params[:sort] point to a key for a hash of predefined sort options.

sort_options = { 'name_up' => 'name ASC, created_at DESC', 'name_down'=>'name DESC, created_at DESC'}

then use

Object.find(:all, :order=>sort_options[params[:sort]])

If the :sort parameter is messed up, it will return the Hash.default.

_Kevin

Here is the epilogue - I created this module (comments removed):

def set_sort_method(model)    unless params[:sort_by].nil?      if model.column_names.include?(params[:sort_by])        @sort_by = params[:sort_by]      end      unless session[:sort_by].nil?        if session[:sort_by] == @sort_by          @sort_by += ' desc'        end      end      session[:sort_by] = @sort_by

You might want to do...

session[:sort_by][model]....

here and a couple of lines up to avoid any conflicts arrising from multiple browser windows open to different pages, etc...

Personally, I would stick with Kevin's suggestion on "sorting names" and here is why:

1. Chris' solution doesn't allow to handle multiple sort params (e.g. 'company desc, name asc') 2. Kevin's solution IMHO is more flexible and secure. 3. Danny, probably, right but it's not straight forward.

Chris Gernon wrote:

Maxim Kulkin wrote: > Personally, I would stick with Kevin's suggestion on "sorting names" and > here is why: > > 1. Chris' solution doesn't allow to handle multiple sort params (e.g. > 'company > desc, name asc') > 2. Kevin's solution IMHO is more flexible and secure.

What would be the best way to implement this? Give each model a class method (called "sort_hash" or something) that returns the hash Kevin describes?

-- Posted via http://www.ruby-forum.com/.

You could do that. I tend to customize the hash for each particular view (or I only ever use it in one), so I just define it right in the view action. In my view, this is part of the 'view' part of MVC, so the model should probably not be aware of it.

_Kevin

Personally, I had this "hash" in my controller which should show my corresponding model data. You see, it's not a generic way to order collections (you have :order param already). It's, IMHO, handy way to make sure that no sql injection will occur.