Module: BulkInsertActiveRecord

Defined in:
lib/bulk-insert-active-record.rb,
lib/inserters.rb,
lib/inserters/base.rb,
lib/inserters/oracle.rb

Overview

Extends the given base class (a subclass of ActiveRecord::Base) with a bulk_insert() class method.

Defined Under Namespace

Modules: Inserters

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object

rubocop:disable Metrics/MethodLength



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/bulk-insert-active-record.rb', line 7

def self.included(base)
  base.class_eval do
    def self.bulk_insert(records, columns = column_names)
      raise('No connection with the database') unless connection.active?

      inserter = Inserters.factory(self)
      transaction do
        if inserter.nil?
          insert_one_by_one(records, columns)
        else
          inserter.execute(records, columns)
        end
      end
    end

    def self.insert_one_by_one(records, column_names)
      records.each do |record|
        if record.is_a?(self)
          record.save
        else
          item = new
          column_names.each_with_index do |column_name, index|
            item[column_name] = record[index]
          end
          item.save
        end
      end
    end
  end
end