How to escape for MYSQL queries from Ruby on Rails?

escaping, mysql, ruby-on-rails

Solution

You can use ActiveRecord's `quote` method (e.g. `ActiveRecord::Base.connection.quote("string with ' apostrophe")`), but ActiveRecord's query methods already escape your SQL for you. For example:

a = "string with ' apostrophe"
ModelName.where("field1 = ?", a)

will change "string with ' apostrophe" to "string with '' apostrophe"

Problem

When searching the MYSQL database for a Rails 2.3.14 app, I need to escape the search string appropriately so I can search for strings containing single-quotes (apostrophes). What's the best way to do this? I'm using the `mysql` gem, in case that matters.

Original source