Question

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 ready method to do it.

Was it helpful?

Solution

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.

OTHER TIPS

In Rails >= 3.2.5 the following works for me:

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top