How to escape for MYSQL queries from Ruby on Rails?
Solution 1
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"
Solution 2
Rails quotes strings as follows:
# Quotes a string, escaping any ' (single quote) and \ (backslash) characters.
def quote_string(s)
s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
end
Solution 3
When using the mysql
gem, you gain the method Mysql.escape_string()
. Use as follows:
search_terms = Mysql.escape_string("it's working!")
conditions = [ "table1.name LIKE '%#{search_terms}%'" ]
# use conditions for MYSQL query as appropriate
joanwolk
I learn fast: I started teaching myself Ruby on Rails and associated technologies in January 2011. I interned with Upstream Agile in mid-2011, and by November 2011 I started a position as a junior developer at mediapeers, where I quickly progressed to a key member of the team. When we changed our tech stack, I moved to focus on the frontend, where implementing designs precisely and elegantly gives me great satisfaction. Before moving to Germany, I worked as a professional stage manager, where I honed my skills in scheduling, organization, and communication before eventually leaving the field in search of something with better hours. Web development was something I explored briefly in college, and I'm really glad I've come back to it.
Updated on July 27, 2022Comments
-
joanwolk almost 2 years
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.