Rails 4 - 在SQL查询中使用LIKE运算符防止SQL注入

Vee*_*Vee 4 sql-injection params ruby-on-rails-4 sql-like

我想对我的Rails 4应用程序使用以下查询,但我担心SQL注入攻击:

@persons = People.where("persons.name LIKE ?", "%#{params[:search]}%")
Run Code Online (Sandbox Code Playgroud)

有人能告诉我写上述陈述的安全方法吗?我尝试了以下但不确定它是否是SQL注入证明:

search = "%" + params[:search] + "%"
@persons = People.where("persons.name LIKE ?", search)
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mig*_*ore 9

zishe说,你的例子很好.

每当您对方法使用问号并将其他参数作为搜索查询传递时,它都会清理您的查询字符串.

手动执行字符串连接以创建查询时很危险,例如:

Project.where("name = '#{params[:name]}'")
Run Code Online (Sandbox Code Playgroud)

点击这里查看更多信息


zis*_*she 6

你的陈述都是安全的.你也可以像这样写:

@persons = People.where("persons.name LIKE concat('%', ?, '%')", params[:search])
Run Code Online (Sandbox Code Playgroud)

Simlilar qestion