Class: M2MFastInsert::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/m2m_fast_insert/base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, join_column_name, table_name, join_table, *args) ⇒ Base

Returns a new instance of Base.

Raises:

  • (ArgumentError)


5
6
7
8
9
10
11
12
13
14
# File 'lib/m2m_fast_insert/base.rb', line 5

def initialize(id, join_column_name, table_name, join_table, *args)
  @options = args[1].present? ? args[1] : {}
  @id = id.to_i
  @ids = args[0].collect(&:to_i)
  @ids.uniq! if options[:unique]
  raise ArgumentError, "Can't have nil ID, perhaps you didn't save the record first?" if id.nil?
  @join_table = join_table
  @join_column_name = join_column_name
  @table_name = table_name
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



3
4
5
# File 'lib/m2m_fast_insert/base.rb', line 3

def id
  @id
end

#idsObject (readonly)

Returns the value of attribute ids.



3
4
5
# File 'lib/m2m_fast_insert/base.rb', line 3

def ids
  @ids
end

#join_column_nameObject (readonly)

Returns the value of attribute join_column_name.



3
4
5
# File 'lib/m2m_fast_insert/base.rb', line 3

def join_column_name
  @join_column_name
end

#join_tableObject (readonly)

Returns the value of attribute join_table.



3
4
5
# File 'lib/m2m_fast_insert/base.rb', line 3

def join_table
  @join_table
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/m2m_fast_insert/base.rb', line 3

def options
  @options
end

#table_nameObject (readonly)

Returns the value of attribute table_name.



3
4
5
# File 'lib/m2m_fast_insert/base.rb', line 3

def table_name
  @table_name
end

Instance Method Details

#fast_insertObject



29
30
31
# File 'lib/m2m_fast_insert/base.rb', line 29

def fast_insert
  ActiveRecord::Base.connection.execute(sql) unless ids.empty?
end

#insertsObject



16
17
18
19
20
21
22
23
# File 'lib/m2m_fast_insert/base.rb', line 16

def inserts
  @inserts ||= begin inserts = []
                 ids.each do |given_id|
                   inserts << "(#{id}, #{given_id})"
                 end
                 inserts.join ", "
               end
end

#sqlObject



25
26
27
# File 'lib/m2m_fast_insert/base.rb', line 25

def sql
  "INSERT INTO #{join_table} (`#{table_name}_id`, `#{join_column_name}_id`) VALUES #{inserts}"
end