Class: ActiveType::NestedAttributes::Association

Inherits:
Object
  • Object
show all
Defined in:
lib/active_type/nested_attributes/association.rb

Direct Known Subclasses

NestsManyAssociation, NestsOneAssociation

Instance Method Summary collapse

Constructor Details

#initialize(owner, target_name, options = {}) ⇒ Association

Returns a new instance of Association.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/active_type/nested_attributes/association.rb', line 11

def initialize(owner, target_name, options = {})
  options.assert_valid_keys(*valid_options)

  @owner = owner
  @target_name = target_name.to_sym
  @allow_destroy = options.fetch(:allow_destroy, false)
  @reject_if = options.delete(:reject_if)
  @options = options.dup
  @index_errors = if ActiveRecord::VERSION::MAJOR < 5
    @options[:index_errors]
  else
    @options[:index_errors] || ActiveRecord::Base.index_nested_attribute_errors
  end
end

Instance Method Details

#assign_attributes(parent, attributes) ⇒ Object

Raises:

  • (NotImplementedError)


26
27
28
# File 'lib/active_type/nested_attributes/association.rb', line 26

def assign_attributes(parent, attributes)
  raise NotImplementedError
end

#save(parent) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/active_type/nested_attributes/association.rb', line 30

def save(parent)
  keep = assigned_children(parent)
  changed_children(parent).each do |child|
    if child.marked_for_destruction?
      child.destroy if child.persisted?
      keep.delete(child)
    else
      child.save(:validate => false) or raise ActiveRecord::Rollback
    end
  end
  assign_children(parent, keep)
end

#validate(parent) ⇒ Object



43
44
45
46
47
# File 'lib/active_type/nested_attributes/association.rb', line 43

def validate(parent)
  changed_children(parent).each_with_index do |child, index|
    add_errors_to_parent(parent, child, index) unless child.valid?
  end
end