Module: Para::AttributeField::NestedField

Included in:
NestedManyField, NestedOneField
Defined in:
lib/para/attribute_field/nested_field.rb

Instance Method Summary collapse

Instance Method Details

#nested_attributes_keyObject



18
19
20
# File 'lib/para/attribute_field/nested_field.rb', line 18

def nested_attributes_key
  @nested_attributes_key ||= :"#{ name }_attributes"
end

#nested_model_mappings(nested_attributes, resource) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/para/attribute_field/nested_field.rb', line 4

def nested_model_mappings(nested_attributes, resource)
  model = if resource
    resource.class
  elsif (type = nested_attributes[:type]).present?
    nested_attributes[:type].try(:constantize)
  else
    reflection.klass
  end

  mappings = attributes_mappings_for(nested_attributes)

  AttributeFieldMappings.new(model, mappings: mappings)
end

#temporarily_extend_new_resource(resource, attributes) ⇒ Object

This method extends the current resource so its #id method returns a fake id based on the given attributes, but immediately returns to its standard behavior of returning nil as soon as the ‘#assign_attributes` method is called.

During nested attributes assignation, the id of the resource is used to assign it its nested params. When it is nil, a new resource is created, but since we already need our resource to be created at the time we parse the input params, we fake the presence of an id while the nested attributes assignation is running, and remove that behavior as soon as we don’t need it anymore.



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/para/attribute_field/nested_field.rb', line 34

def temporarily_extend_new_resource(resource, attributes)
  resource.instance_variable_set(:@_waiting_for_attributes_assignation, true)

  resource.define_singleton_method(:assign_attributes) do |*args|
    @_waiting_for_attributes_assignation = false
    super(*args)
  end

  resource.define_singleton_method(:id) do
    @_waiting_for_attributes_assignation ? attributes['id'] : read_attribute(:id)
  end
end