Escaping values in Rails (similar to mysql_real_escape_string())

后端 未结 6 1838
我在风中等你
我在风中等你 2020-12-14 00:54

I know about prepared statements, but if I\'m using raw SQL, does ActiveRecord have a way to manually escape values?

Something like this would be nice:



        
6条回答
  •  隐瞒了意图╮
    2020-12-14 01:33

    You can easily use the mysql2 gem to do this:

    irb(main):002:0> require 'rubygems'
    => true
    irb(main):003:0> require 'mysql2'
    => true
    irb(main):004:0> Mysql2::Client.escape("O'Malley") # => "O\\'Malley"
    => "O\\'Malley"
    

    Or if using the earlier mysql (not mysql2) gem:

    irb(main):002:0> require 'rubygems'
    => true
    irb(main):003:0> require 'mysql'
    => true
    irb(main):004:0> Mysql.escape_string("O'Malley")
    => "O\\'Malley"
    

    This will allow you to escape anything you want then insert to the db. You can also do this on most models in your rails application using the sanitize method. For instance say you have a model called Person. You could do.

    Person.sanitize("O'Malley")
    

    That should do the trick.

提交回复
热议问题