Module: DataMapper::NestedAttributes::Model

Defined in:
lib/dm-accepts_nested_attributes/model.rb

Instance Method Summary collapse

Instance Method Details

#accepts_nested_attributes_for(association_name, options = {}) ⇒ Object

Allows any association to accept nested attributes.

Parameters:

  • The name of the association that should accept nested attributes

  • (defaults to: {})

    List of resources to initialize the Collection with

  • a customizable set of options

  • a customizable set of options

Returns:

  • nil

Raises:

  • A named exception class indicating invalid options



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/dm-accepts_nested_attributes/model.rb', line 35

def accepts_nested_attributes_for(association_name, options = {})

  # ----------------------------------------------------------------------------------
  #                      try to fail as early as possible
  # ----------------------------------------------------------------------------------

  unless relationship = relationships(repository_name)[association_name]
    raise(ArgumentError, "No relationship #{association_name.inspect} for '#{name}' in :#{repository_name} repository")
  end

  # raise InvalidOptions if the given options don't make sense
  assert_valid_options_for_nested_attributes(options)

  # by default, nested attributes can't be destroyed
  options = { :allow_destroy => false }.update(options)

  # ----------------------------------------------------------------------------------
  #                       should be safe to go from here
  # ----------------------------------------------------------------------------------

  options_for_nested_attributes[relationship] = options

  include ::DataMapper::NestedAttributes::Resource

  type = relationship.max > 1 ? :collection : :resource

  define_method "#{association_name}_attributes" do
    instance_variable_get("@#{association_name}_attributes")
  end

  define_method "#{association_name}_attributes=" do |attributes|
    attributes = sanitize_nested_attributes(attributes)
    instance_variable_set("@#{association_name}_attributes", attributes)
    send("assign_nested_attributes_for_related_#{type}", relationship, attributes)
  end

end

#options_for_nested_attributesObject



73
74
75
# File 'lib/dm-accepts_nested_attributes/model.rb', line 73

def options_for_nested_attributes
  @options_for_nested_attributes ||= {}
end