1

I'm trying to get the following request sanitized to send to a MySQL server:

  INSERT INTO `table`
  SELECT NULL, t.`id`, ?, ?
  FROM `table` AS t
  WHERE t.`some_field` = ?

The tricky part is that that request is to be executed in a class that is not my model class. It looks like this:

class Model < 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

I've seen a lot of people using Model#sanitize_sql, but this is a protected method, which is unusable in my context.

Any idea?

EDIT:

It has been suggested that my question might be a duplicate of this one. I've seen this question before posting, but the answers provided there aren't relevant in my case: I don't want to use quote 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 INSERT...SELECT query. (This question seems to confirm it)

Community
  • 1
  • 1
Richard-Degenne
  • 2,892
  • 2
  • 26
  • 43
  • Possible duplicate of [How to sanitize sql fragment in Rails](http://stackoverflow.com/questions/3009023/how-to-sanitize-sql-fragment-in-rails) – Roman Kiselenko Mar 30 '17 at 15:41
  • How does `run` actually look like when it generates that SQL query? Why can't you generate the query in the Model itself with standard Rails methods? – spickermann Mar 30 '17 at 15:41
  • @Зелёный, I've seen this question, it doesn't address my problem. – Richard-Degenne Mar 30 '17 at 15:43
  • @spickermann, I'm not using Rails, and I have to export higher order logic outside of the model itself. As far as OOP is concerned, the Model has nothing to do with the algorithm `run` represents. Also, I don't think ActiveRecord is capable of generating an `INSERT...SELECT` query, which is why I resort to raw SQL here. – Richard-Degenne Mar 30 '17 at 15:45
  • I found [this](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-to_sql), which may well be what I'm looking for, but I can't get it right, and the documentation isn't really helping either. – Richard-Degenne Mar 31 '17 at 13:17

0 Answers0