Search code examples
rubyactiverecordsql-injectionmysql-real-escape-string

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


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.