title: Sanitize raw SQL with ActiveRecord
body: <p>I'm trying to get the following request sanitized to send to a MySQL server:</p>
  
  <pre><code>  INSERT INTO `table`
    SELECT NULL, t.`id`, ?, ?
    FROM `table` AS t
    WHERE t.`some_field` = ?
  </code></pre>
  
  <p>The tricky part is that that request is to be executed in a class that <strong>is not</strong> my model class. It looks like this:</p>
  
  <pre><code>class Model &lt; ActiveRecord::Base
    def some_method
      Service.new(self).run
    end
  end
  
  class Service
    def initialize(model)
      @model = model
    end
  
    def run
      # Here is the request
    end
  end
  </code></pre>
  
  <p>I've seen a lot of people using <code>Model#sanitize_sql</code>, but this is a protected method, which is unusable in my context.</p>
  
  <p>Any idea?</p>
  
  <p><strong>EDIT</strong>:</p>
  
  <p>It has been suggested that my question might be a duplicate of <a href="https://stackoverflow.com/questions/34402835/how-to-sanitize-raw-sql-in-rails-4">this one</a>. I've seen this question before posting, but the answers provided there aren't relevant in my case: I don't want to use <a href="http://apidock.com/rails/ActiveRecord/Base/quote_value" rel="nofollow noreferrer"><code>quote</code></a> because most of my fields are going to be numeric values. The other answer suggests not using raw SQL, but, as stated in the comments, I don't think ActiveRecord is capable of generating an <a href="https://dev.mysql.com/doc/refman/5.7/en/insert-select.html" rel="nofollow noreferrer"><code>INSERT...SELECT</code> query</a>. (<a href="https://stackoverflow.com/questions/4768506/can-i-perform-a-insert-select-operation-with-the-rails-api/4877953">This question</a> seems to confirm it)</p>