title: Rails 4 LIKE query with array conditions - apostrophe is escaped with double backslash
body: <p>Having followed some tips on escaping apostrophes I am getting an unexpected combination of escape characters in the resulting sql statement. The following rails 4 active record statement is run against 5.5.42-MariaDB:</p>
  
  <pre><code>    User.where(["surname LIKE ?", "%#{params[:search]}%"])
  </code></pre>
  
  <p>Where </p>
  
  <pre><code>    params[:search] =  "O'Keefe"
  </code></pre>
  
  <p>A <code>.to_sql</code> generates</p>
  
  <pre><code>     SELECT * FROM users WHERE surname LIKE '%O\\'Keefe%'
  </code></pre>
  
  <p>MySQL/MariaBD expects an apostrophe to be escaped as two single apostrophes <code>''</code> , or with a single backslash <code>\'</code> so this results in a syntax error.  I am looking for help to understand why <strong>two</strong> backslashes <code>\\'</code> are appearing, and for a solution that will maintain protection against SQL injection. </p>
  
  <p><strong>UPDATE</strong>
  After further investigation following suggestions below, it appears as though the console <code>.to_sql</code> output <code>SELECT * FROM users WHERE surname LIKE '%O\\'Keefe%'</code> is not what is passed onto MySQL. It failed for me 'cos I simply copied the statement into a mysql console to test execution. There is some black magic on route to the database that converts the double backslash <code>\\'</code> into a valid mysql escape sequence.</p>
  
  <p>So problem 1/2 solved</p>
  
  <pre><code>    User.where(["surname LIKE ?", "%#{params[:search]}%"])
  </code></pre>
  
  <p>is valid syntax that correctly auto-escapes the user input string.  But can anyone shed any light on the reason for the generation of the double backslash and how it is modified on its way to database execution?</p>