accepts_nested_attributes_for

accepts_nested_attributes_for(*attr_names)
Instance Public methods

Defines an attributes writer for the specified association(s).

Supported options:

:allow_destroy

If true, destroys any members from the attributes hash with a _destroy key and a value that evaluates to true (eg. 1, '1', true, or 'true'). This option is off by default.

:reject_if

Allows you to specify a Proc or a Symbol pointing to a method that checks whether a record should be built for a certain attribute hash. The hash is passed to the supplied Proc or the method and it should return either true or false. When no :reject_if is specified, a record will be built for all attribute hashes that do not have a _destroy value that evaluates to true. Passing :all_blank instead of a Proc will create a proc that will reject a record where all the attributes are blank excluding any value for _destroy.

:limit

Allows you to specify the maximum number of the associated records that can be processed with the nested attributes. Limit also can be specified as a Proc or a Symbol pointing to a method that should return number. If the size of the nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords exception is raised. If omitted, any number associations can be processed. Note that the :limit option is only applicable to one-to-many associations.

:update_only

For a one-to-one association, this option allows you to specify how nested attributes are to be used when an associated record already exists. In general, an existing record may either be updated with the new set of attribute values or be replaced by a wholly new record containing those values. By default the :update_only option is false and the nested attributes are used to update the existing record only if they include the record's :id value. Otherwise a new record will be instantiated and used to replace the existing one. However if the :update_only option is true, the nested attributes are used to update the record's attributes always, regardless of whether the :id is present. The option is ignored for collection associations.

Examples:

# creates avatar_attributes=
accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? }
# creates avatar_attributes=
accepts_nested_attributes_for :avatar, reject_if: :all_blank
# creates avatar_attributes= and posts_attributes=
accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
doc_ruby_on_rails
2015-06-20 00:00:00
Comments
Leave a Comment

Please login to continue.