简体   繁体   English

如何在Ruby中插入或更新之前转义字符串

[英]how to escape a string before insert or update in Ruby

In ruby ActiveRecord doesn't provide dynamic binding for update and insert sqls, of course i can use raw sql, but that need maintain connection, so i want to know if there is simpler way to escape update or insert sql before executing like code below: 在ruby中ActiveRecord不提供动态绑定更新和插入sqls,当然我可以使用原始sql,但是需要维护连接,所以我想知道是否有更简单的方法来逃避更新或插入sql之前执行下面的代码:

ActiveRecord::Base.connection.insert(sql)

i think i can write code by gsub, but i know if there has been a ready method to do it. 我想我可以用gsub编写代码,但我知道是否有一个现成的方法来做到这一点。

In Rails >= 3.2.5 the following works for me: 在Rails> = 3.2.5中,以下内容适用于我:

evil_input = '"\';%#{}\"foo'
ActiveRecord::Base.connection.quote(evil_input)
=> "'\"'';%\#{}\\\"foo'"

You could do this: 你可以这样做:

ActiveRecord::Base.send(:sanitize_sql,["select * from my_table where description='%s' and id='%s'","mal'formed", 55], "my_table")

Of course, this means that you have the params separately. 当然,这意味着您可以单独使用params。 Not sure if it will work otherwise, but try it out. 不确定它是否会起作用,但试试看。

It's not real clear what you are asking for because your title talks about escaping a string before insert or update, then in the tags you talk about SQL injection. 你要求的并不是很明确,因为你的标题谈到在插入或更新之前转义字符串,然后在标签中谈论SQL注入。

If you need to have ActiveRecord automatically encode/modify content before insertion or updating, have you checked ActiveRecord's Callbacks ? 如果您需要在插入或更新之前让ActiveRecord自动编码/修改内容,您是否检查过ActiveRecord的回调 The before_save callback will fire when you do an update or create. 执行更新或创建时,将触发before_save回调。 If you want to modify the content before it's to be stored, that's a good place to do it. 如果您想在存储之前修改内容,那么这是一个很好的做法。

If you want to use SQL parameters instead of inserting the variables into your "update" or "insert" statements to avoid SQL injection, then use AR's variable bindings . 如果要使用SQL参数而不是将变量插入“update”或“insert”语句以避免SQL注入,则使用AR的变量绑定 Scroll down to the section on "Conditions". 向下滚动到“条件”部分。

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

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