简体   繁体   English

如何防止 SQL 在以下轨道查询中注入?

[英]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.首先不使用 SQL 字符串。 You can create a WHERE clause by passing a hash instead:您可以通过传递 hash 来创建WHERE子句:

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:如果您绝对觉得需要使用 SQL 字符串,请使用占位符而不是字符串插值:

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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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