How to avoid MYSQL queries from Ruby on Rails?

When searching the MYSQL database for a Rails 2.3.14 application, I need to avoid the search string appropriately so that I can search for strings containing single quotes (apostrophes). What is the best way to do this? I use stone mysqlif that matters.

+5
source share
3 answers

You can use the ActiveRecord method quote(for example, ActiveRecord::Base.connection.quote("string with ' apostrophe")), but ActiveRecord query methods already avoid your SQL code for you. For instance:

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

will change a line with an apostrophe to a line with an apostrophe

+5
source

When using a gem, mysqlyou get a method Mysql.escape_string(). Use the following:

search_terms = Mysql.escape_string("it working!")
conditions = [ "table1.name LIKE '%#{search_terms}%'" ]
# use conditions for MYSQL query as appropriate
+8
source

Rails :

# Quotes a string, escaping any ' (single quote) and \ (backslash) characters.
def quote_string(s)
  s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
end
+8

All Articles