Is ActiveRecord's “order” method vulnerable to SQL injection?

后端 未结 5 2204
我寻月下人不归
我寻月下人不归 2020-12-17 10:32

I know it\'s not safe to use interpolated strings when calling .where.

e.g. this:

Client.where(\"orders_count = #{params[:orders]}\")

5条回答
  •  悲&欢浪女
    2020-12-17 11:14

    Let's try this!

    # app/models/concern/ext_active_record.rb
    module ExtActiveRecord
        extend ActiveSupport::Concern
    
        included do
            scope :sortable, -> (params) do
                return unless params[:sort_by] && params[:sort_dir]
                reorder("#{params[:sort_by]}" => "#{params[:sort_dir]}")
            end
        end
    end
    
    # app/models/user.rb
    class User < ActiveRecord::Base
        include ExtActiveRecord
        # ....
    end
    
    # app/controllers/user_controller.rb
    class UserController < ApplicationController
        def index
            @users = User.sortable(params).page(params[:page]).per(params[:per])
        end
    end
    

提交回复
热议问题