Class: ActiveRecord::Associations::HasAndBelongsToManyAssociation

Inherits:
CollectionAssociation show all
Defined in:
activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Attributes inherited from Association

#owner, #reflection, #target

Instance Method Summary collapse

Methods inherited from CollectionAssociation

#add_to_target, #any?, #build, #concat, #count, #create, #create!, #delete, #delete_all, #destroy, #destroy_all, #distinct, #empty?, #find, #first, #ids_reader, #ids_writer, #include?, #last, #length, #load_target, #many?, #null_scope?, #reader, #replace, #reset, #scope, #select, #size, #transaction, #writer

Methods inherited from Association

#aliased_table_name, #association_scope, #initialize_attributes, #interpolate, #klass, #load_target, #loaded!, #loaded?, #marshal_dump, #marshal_load, #reload, #reset, #reset_scope, #scope, #set_inverse_instance, #stale_target?, #target_scope

Constructor Details

#initialize(owner, reflection) ⇒ HasAndBelongsToManyAssociation

Returns a new instance of HasAndBelongsToManyAssociation


7
8
9
10
# File 'activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb', line 7

def initialize(owner, reflection)
  @join_table = Arel::Table.new(reflection.join_table)
  super
end

Instance Attribute Details

#join_tableObject (readonly)

Returns the value of attribute join_table


5
6
7
# File 'activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb', line 5

def join_table
  @join_table
end

Instance Method Details

#insert_record(record, validate = true, raise = false) ⇒ Object


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb', line 12

def insert_record(record, validate = true, raise = false)
  if record.new_record?
    if raise
      record.save!(:validate => validate)
    else
      return unless record.save(:validate => validate)
    end
  end

  stmt = join_table.compile_insert(
    join_table[reflection.foreign_key]             => owner.id,
    join_table[reflection.association_foreign_key] => record.id
  )

  owner.class.connection.insert stmt

  record
end