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
25
26
27
28
# 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 = case
                  when ActiveRecord::VERSION::MAJOR < 5
                    @options[:index_errors]
                  when ActiveRecord::VERSION::MAJOR < 7
                    @options[:index_errors] || ActiveRecord::Base.index_nested_attribute_errors
                  else
                    @options[:index_errors] || ActiveRecord.index_nested_attribute_errors
                  end
end

Instance Method Details

#assign_attributes(parent, attributes) ⇒ Object

Raises:

  • (NotImplementedError)


30
31
32
# File 'lib/active_type/nested_attributes/association.rb', line 30

def assign_attributes(parent, attributes)
  raise NotImplementedError
end

#save(parent) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/active_type/nested_attributes/association.rb', line 34

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



47
48
49
50
51
# File 'lib/active_type/nested_attributes/association.rb', line 47

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