Class: ActiveRecord::Associations::HasAndBelongsToManyAssociation

Inherits:
Object
  • Object
show all
Defined in:
lib/octopus/has_and_belongs_to_many_association.rb

Instance Method Summary collapse

Instance Method Details

#insert_record(record, force = true, validate = true) ⇒ Object



6
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
37
38
39
40
41
42
# File 'lib/octopus/has_and_belongs_to_many_association.rb', line 6

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

  if @reflection.options[:insert_sql]
    @owner.connection.insert(interpolate_sql(@reflection.options[:insert_sql], record))
  else
    relation = Arel::Table.new(@reflection.options[:join_table])
    attributes = columns.inject({}) do |attrs, column|
      case column.name.to_s
      when @reflection.primary_key_name.to_s
        attrs[relation[column.name]] = owner_quoted_id
      when @reflection.association_foreign_key.to_s
        attrs[relation[column.name]] = record.quoted_id
      else
        if record.has_attribute?(column.name)
          value = @owner.send(:quote_value, record[column.name], column)
          attrs[relation[column.name]] = value unless value.nil?
        end
      end
      attrs
    end
    
    if should_wrap_the_connection?
      @owner.using(@owner.current_shard) { relation.insert(attributes) } 
    else
      relation.insert(attributes)
    end
  end

  return true
end

#should_wrap_the_connection?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/octopus/has_and_belongs_to_many_association.rb', line 2

def should_wrap_the_connection?
  @owner.respond_to?(:current_shard) && @owner.current_shard != nil
end