开发者

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:

ActiveRecord::Base.connection.insert(sql)

i think i can write code by gsub, but i know if there has been a 开发者_如何学Cready method to do it.


In Rails >= 3.2.5 the following works for me:

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. 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.

If you need to have ActiveRecord automatically encode/modify content before insertion or updating, have you checked ActiveRecord's Callbacks? The before_save callback will fire when you do an update or create. 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. Scroll down to the section on "Conditions".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜