Module: ActiveRecord::BatchInsert::ClassMethods

Defined in:
lib/batch_insert.rb

Instance Method Summary collapse

Instance Method Details

#batch_insertObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/batch_insert.rb', line 10

def batch_insert
  self.batched_inserts = returning(batched_inserts) do
    self.batched_inserts = []
    yield

    unless self.batched_inserts.empty?
      column_names = columns.map(&:name).sort - [primary_key]
      connection.execute %Q{
        INSERT INTO #{connection.quote_table_name(table_name)}
        (#{column_names.map{|n| connection.quote_column_name(n)}.join(',')})
        VALUES
        #{batch_insert_values_string(column_names)}
      }.gsub(/\s+/,' ').squeeze(' ').strip
    end
  end
end

#batch_insert_values_string(column_names) ⇒ Object



27
28
29
30
31
# File 'lib/batch_insert.rb', line 27

def batch_insert_values_string(column_names)
  self.batched_inserts.collect do |attributes|
    "(#{column_names.map{|n| attributes[n]}.collect{|v|quote_value(v)}.join(',')})"
  end.join ','
end

#insert(opts = {}) ⇒ Object



33
34
35
36
37
38
# File 'lib/batch_insert.rb', line 33

def insert(opts={})
  returning new(opts) do |obj|
    raise RecordInvalid.new(obj) unless obj.valid?
    self.batched_inserts << obj.attributes
  end
end