Module: ActiveRecord::MassAssignmentSecurity::NestedAttributes::ClassMethods

Defined in:
lib/active_record/mass_assignment_security/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



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/active_record/mass_assignment_security/nested_attributes.rb', line 10

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|
    if reflection = reflect_on_association(association_name)
      if active_record_40?
        reflection.options[:autosave] = true
      else
        reflection.autosave = true
      end
      add_autosave_association_callbacks(reflection)

      nested_attributes_options = self.nested_attributes_options.dup
      nested_attributes_options[association_name.to_sym] = options
      self.nested_attributes_options = nested_attributes_options

      type = (reflection.collection? ? :collection : :one_to_one)

      generated_methods_module = active_record_40? ? generated_feature_methods : generated_association_methods

      # def pirate_attributes=(attributes)
      #   assign_nested_attributes_for_one_to_one_association(:pirate, attributes, mass_assignment_options)
      # end
      generated_methods_module.module_eval <<-eoruby, __FILE__, __LINE__ + 1
        if method_defined?(:#{association_name}_attributes=)
          remove_method(:#{association_name}_attributes=)
        end
        def #{association_name}_attributes=(attributes)
          assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes, mass_assignment_options)
        end
      eoruby
    else
      raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
    end
  end
end