Converting a Rails model to SQL inserts a query?

Is there a way to convert the Rails model into an insert request?

For example, if I have a model, for example:

m = Model.new
m.url = "url"
m.header = "header"

How can I get the corresponding ActiveRecord SQL query if I made m.save?

I want to get: "INSERT INTO models (url, header) VALUES ('url', 'header')", if possible.

Note. I do not want to actually save the model and return the request (from a log file, etc.). I want to receive a request if I decide to save it.

+5
source share
4 answers

Rails 3.2.13: , , . , , , , - .

lib insert_sqlable.rb,

#in your models or you can send it to ActiveRecord::Base
include InsertSqlable

model.insert_sql, .

#lib/insert_sqlable
module InsertSqlable
    def insert_sql
      values = arel_attributes_values
      primary_key_value = nil

      if self.class.primary_key && Hash === values
        primary_key_value = values[values.keys.find { |k|
          k.name == self.class.primary_key
        }]

        if !primary_key_value && connection.prefetch_primary_key?(self.class.table_name)
          primary_key_value = connection.next_sequence_value(self.class.sequence_name)
          values[self.class.arel_table[self.class.primary_key]] = primary_key_value
        end
      end

      im = self.class.arel_table.create_insert
      im.into self.class.arel_table

      conn = self.class.connection

      substitutes = values.sort_by { |arel_attr,_| arel_attr.name }
      binds       = substitutes.map do |arel_attr, value|
        [self.class.columns_hash[arel_attr.name], value]
      end

      substitutes.each_with_index do |tuple, i|
        tuple[1] = conn.substitute_at(binds[i][0], i)
      end

      if values.empty? # empty insert
        im.values = Arel.sql(self.class.connectionconnection.empty_insert_statement_value)
      else
        im.insert substitutes
      end

      conn.to_sql(im,binds)
    end
end

, ActiveRecord:: Relation, ActiveRecord:: Persistence. - , sql .

+2

Rails 4.1 :

record = Post.new(:title => 'Yay', :body => 'This is some insert SQL')

record.class.arel_table.create_insert
  .tap { |im| im.insert(record.send(
            :arel_attributes_with_values_for_create,
            record.attribute_names)) }
  .to_sql

https://coderwall.com/p/obrxhq/how-to-generate-activerecord-insert-sql

+6

, m.destroy, .

SQL-,

Rails.logger.debug " INSERT INTO (url, header) VALUES (# {m.url}, # {m.header}).

0

, , : .

, , , Rails 3.2 . , . , Rails 4.0, .

"models-to-sql-rails" , Rails 4.0 .


. ( - , ).

:

object.to_sql_insert
# INSERT INTO modelName (field1, field2) VALUES ('Wow, amaze gem', 'much doge')

:

array_of_objects.to_sql_insert
# INSERT INTO modelName (field1, field2) VALUES ('Awesome doge', "im fucking cop")
# INSERT INTO modelName (field1, field2) VALUES ('much profit', 'much doge')
# (...)

Just look at the Github of this project and you will find how to install and use this wonderful stone.

0
source

All Articles