Module: Formed::NestedAttributes::ClassMethods

Defined in:
lib/formed/nested_attributes.rb

Constant Summary collapse

REJECT_ALL_BLANK_PROC =
proc { |attributes| attributes.all? { |key, value| key == "_destroy" || value.blank? } }

Instance Method Summary collapse

Instance Method Details

#accepts_nested_attributes_for(*attr_names) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/formed/nested_attributes.rb', line 78

def accepts_nested_attributes_for(*attr_names)
  options = { allow_destroy: false, update_only: false }
  options.update(attr_names.extract_options!)
  options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
  options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank

  attr_names.each do |association_name|
    unless (reflection = _reflect_on_association(association_name))
      raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
    end

    nested_attributes_options = self.nested_attributes_options.dup
    nested_attributes_options[association_name.to_sym] = options
    self.nested_attributes_options = nested_attributes_options
    define_validation_callbacks(reflection)

    type = (reflection.collection? ? :collection : :one_to_one)
    generate_association_writer(association_name, type)
  end
end