rails 3 activerecord order – what is the proper sql injection work around?

Ryan Bates’ method:

in your controller:

def index
  @users = User.order(sort_by + " " + direction)
end

private
  def sort_by
    %w{email name}.include?(params[:sort_by]) ? params[:sort_by] : 'name'
  end

  def direction
    %w{asc desc}.include?(params[:direction]) ? params[:direction] : 'asc'
  end

Essentially you’re making a whitelist, but it’s easy to do and insusceptible to injection.

Leave a Comment