Class: ActiveRecord::Associations::CollectionAssociation

Inherits:
Object
  • Object
show all
Defined in:
ext/active_record/associations/collection_association.rb

Instance Method Summary collapse

Instance Method Details

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



45
46
47
48
49
50
51
52
53
# File 'ext/active_record/associations/collection_association.rb', line 45

def insert_record(record, validate = true, raise = false, &block)
  if record.class.connection.is_a?(ActiveRecord::ConnectionAdapters::SunstoneAPIAdapter) && owner.instance_variable_defined?(:@sunstone_updating) && owner.instance_variable_get(:@sunstone_updating)
    true
  elsif raise
    record.save!(validate: validate, &block)
  else
    record.save(validate: validate, &block)
  end
end

#replace(other_array) ⇒ Object



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
43
# File 'ext/active_record/associations/collection_association.rb', line 7

def replace(other_array)
  other_array.each { |val| raise_on_type_mismatch!(val) }
  original_target = skip_strict_loading { load_target }.dup

  if owner.new_record?
    replace_records(other_array, original_target)
  elsif owner.class.connection.is_a?(ActiveRecord::ConnectionAdapters::SunstoneAPIAdapter) && owner.instance_variable_defined?(:@sunstone_updating) && owner.instance_variable_get(:@sunstone_updating)
    replace_common_records_in_memory(other_array, original_target)

    # Remove from target
    records_for_removal = (original_target - other_array)
    if !records_for_removal.empty?
      self.instance_variable_set(:@sunstone_changed, true)
      records_for_removal.each { |record| callback(:before_remove, record) }
      records_for_removal.each { |record| target.delete(record) }
      records_for_removal.each { |record| callback(:after_remove, record) }
    end

    # Add to target
    records_for_addition = (other_array - original_target)
    if !records_for_addition.empty?
      self.instance_variable_set(:@sunstone_changed, true)
      (other_array - original_target).each do |record|
        add_to_target(record)
      end
    end

    other_array
  else
    replace_common_records_in_memory(other_array, original_target)
    if other_array != original_target
      transaction { replace_records(other_array, original_target) }
    else
      other_array
    end
  end
end