简体   繁体   中英

How can I prevent SQL injection in following rails query?

Data is a param in the below statement:

condition = params["id"].present? ? "employers.status = '#{params["id"].upcase}' and employers.task = '#{data.upcase}'" : "employers.task.rdu = '#{data.upcase}'"

By not using a SQL string in the first place. You can create a WHERE clause by passing a hash instead:

condition = begin do
  if params[:id].present?
    Employer.where(
       status: params[:id].upcase,
       task: data.upcase
    )
  else
    # I have no idea what you're doing with employers.task.rdu
    Employer.where(
      "task.rdu" => data.upcase
    )
  end
end

If you absolutely feel that you need to use a SQL string use placeholders instead of string interpolation:

Employer.where(
  "employers.status = ? and employers.task = ?", params[:id].upcase, data.upcase
)

Employer.where(
  "employers.status = :status and employers.task = :task", 
   status: params[:id].upcase, 
   task: data.upcase
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM