Tip: Escaping single quotes on SQL insert (ruby)

For quite sometime, I haven't tried executing SQLs manually in Rails.  But, try as I may not to create a specific model for this scenario, I just couldn't.

So, in the meantime that I had to do the manual insert, I encountered a problem with strings with single quotes.  Particularly those names that have O', etc.

This gives you an error in SQL insert.

name = "O'Neil"
ActiveRecord::Base.connection.execute("INSERT INTO names (name) values ('" + name + "')")

This one will do the trick:

name = "O'Neil"
ActiveRecord::Base.connection.execute("INSERT INTO names (name) values ('" + ActiveRecord::Base.connection.quote(name) + "')")

Anyhow, to avoid more troubles, just create a model. It does many other tasks for you like this automatic escaping of single quotes, etc.

Maricris Nonato

I turn tech ideas into websites using Ruby. I'm a budding Buddhist practitioner, passionate about health & fitness, and a cat fanatic!