Class: ActiveRecord::Associations::HasManyForActiveModelAssociation

Inherits:
HasManyAssociation
  • Object
show all
Defined in:
lib/active_record/associations/has_many_for_active_model_association.rb

Instance Method Summary collapse

Instance Method Details

#concat(*records) ⇒ Object

no need transaction



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/active_record/associations/has_many_for_active_model_association.rb', line 44

def concat(*records)
  load_target
  flatten_records = records.flatten
  flatten_records.each { |val| raise_on_type_mismatch!(val) }
  target_ids = reflection.options[:target_ids]
  owner[target_ids] ||= []
  owner[target_ids].concat(flatten_records.map(&:id))

  flatten_records.each do |record|
    if index = @target.index(record)
      @target[index] = record
    else
      @target << record
    end
  end

  target
end

#empty?Boolean

not support counter_cache

Returns:

  • (Boolean)


14
15
16
17
18
19
20
# File 'lib/active_record/associations/has_many_for_active_model_association.rb', line 14

def empty?
  if loaded?
    size.zero?
  else
    @target.blank? && !scope.exists?
  end
end

#find_target?Boolean

remove conditions: owner.new_record?, foreign_key_present?

Returns:

  • (Boolean)


4
5
6
# File 'lib/active_record/associations/has_many_for_active_model_association.rb', line 4

def find_target?
  !loaded? && klass
end

#null_scope?Boolean

no dependent action

Returns:

  • (Boolean)


9
10
11
# File 'lib/active_record/associations/has_many_for_active_model_association.rb', line 9

def null_scope?
  false
end

#replace(other_array) ⇒ Object

full replace simplely



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/active_record/associations/has_many_for_active_model_association.rb', line 23

def replace(other_array)
  original_target = load_target.dup
  other_array.each { |val| raise_on_type_mismatch!(val) }
  target_ids = reflection.options[:target_ids]
  owner[target_ids] = other_array.map(&:id)

  old_records = original_target - other_array
  old_records.each do |record|
    @target.delete(record)
  end

  other_array.each do |record|
    if index = @target.index(record)
      @target[index] = record
    else
      @target << record
    end
  end
end