how to escape a string before insert or update in Ruby

ywenbo picture ywenbo · Dec 24, 2010 · Viewed 9.5k times · Source

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.

Answer

rantler picture rantler · Sep 1, 2012

In Rails >= 3.2.5 the following works for me:

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