module ActiveRecord::NestedAttributes::ClassMethods
def accepts_nested_attributes_for(*attr_names)
# creates avatar_attributes= and posts_attributes=
accepts_nested_attributes_for :avatar, :reject_if => :all_blank
# creates avatar_attributes=
accepts_nested_attributes_for :avatar, :reject_if => proc { |attributes| attributes['name'].blank? }
# creates avatar_attributes=
Examples:
collection associations. This option is off by default.
This option only works for one-to-one associations and is ignored for
A new record may only be created when there is no existing record.
Allows you to specify that an existing record may only be updated.
[:update_only]
Note that the :limit option is only applicable to one-to-many associations.
exception is raised. If omitted, any number associations can be processed.
nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
can be processes with the nested attributes. If the size of the
Allows you to specify the maximum number of the associated records that
[:limit]
that will reject a record where all the attributes are blank.
Passing :all_blank instead of a Proc will create a proc
do not have a _destroy value that evaluates to true.
is specified, a record will be built for all attribute hashes that
and it should return either +true+ or +false+. When no :reject_if
hash. The hash is passed to the supplied Proc or the method
that checks whether a record should be built for a certain attribute
Allows you to specify a Proc or a Symbol pointing to a method
[:reject_if]
(eg. 1, '1', true, or 'true'). This option is off by default.
_destroy key and a value that evaluates to +true+
If true, destroys any members from the attributes hash with a
[:allow_destroy]
Supported options:
will need to add the attribute writer to the allowed list.
are using attr_protected or attr_accessible, then you
Defines an attributes writer for the specified association(s). If you
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) reflection.options[:autosave] = true add_autosave_association_callbacks(reflection) nested_attributes_options[association_name.to_sym] = options type = (reflection.collection? ? :collection : :one_to_one) # def pirate_attributes=(attributes) # assign_nested_attributes_for_one_to_one_association(:pirate, attributes) # end class_eval <<-EOS, __FILE__, __LINE__ + 1 def #{association_name}_attributes=(attributes) assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes) end EOS else raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?" end end end