### Home Classes Methods

### In Files

- lib/active_record/nested_attributes.rb

### Methods

- #accepts_nested_attributes_for

### Files

- README.rdoc

### Class/Module Index

Quicksearch

- ActiveRecord
- ActiveRecord::ActiveRecordError
- ActiveRecord::AdapterNotFound
- ActiveRecord::AdapterNotSpecified
- ActiveRecord::Aggregations
- ActiveRecord::Aggregations::ClassMethods
- ActiveRecord::AssociationTypeMismatch
- ActiveRecord::Associations
- ActiveRecord::Associations::ClassMethods
- ActiveRecord::AttributeAssignment
- ActiveRecord::AttributeAssignment::ClassMethods
- ActiveRecord::AttributeAssignmentError
- ActiveRecord::AttributeMethods
- ActiveRecord::AttributeMethods::BeforeTypeCast
- ActiveRecord::AttributeMethods::ClassMethods
- ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead
- ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead::ClassMethods
- ActiveRecord::AttributeMethods::Dirty
- ActiveRecord::AttributeMethods::PrimaryKey
- ActiveRecord::AttributeMethods::PrimaryKey::ClassMethods
- ActiveRecord::AttributeMethods::Query
- ActiveRecord::AttributeMethods::Read
- ActiveRecord::AttributeMethods::Read::ClassMethods
- ActiveRecord::AttributeMethods::Serialization
- ActiveRecord::AttributeMethods::Serialization::Attribute
- ActiveRecord::AttributeMethods::Serialization::ClassMethods
- ActiveRecord::AttributeMethods::TimeZoneConversion
- ActiveRecord::AttributeMethods::TimeZoneConversion::ClassMethods
- ActiveRecord::AttributeMethods::Write
- ActiveRecord::AttributeMethods::Write::ClassMethods
- ActiveRecord::AutosaveAssociation
- ActiveRecord::AutosaveAssociation::ClassMethods
- ActiveRecord::Base
- ActiveRecord::Batches
- ActiveRecord::Calculations
- ActiveRecord::Callbacks
- ActiveRecord::Coders
- ActiveRecord::ConfigurationError
- ActiveRecord::ConnectionAdapters
- ActiveRecord::ConnectionAdapters::AbstractAdapter
- ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
- ActiveRecord::ConnectionAdapters::ConnectionHandler
- ActiveRecord::ConnectionAdapters::ConnectionManagement
- ActiveRecord::ConnectionAdapters::ConnectionPool
- ActiveRecord::ConnectionAdapters::DatabaseLimits
- ActiveRecord::ConnectionAdapters::DatabaseStatements
- ActiveRecord::ConnectionAdapters::Mysql2Adapter
- ActiveRecord::ConnectionAdapters::MysqlAdapter
- ActiveRecord::ConnectionAdapters::MysqlAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils
- ActiveRecord::ConnectionAdapters::PostgreSQLColumn
- ActiveRecord::ConnectionAdapters::QueryCache
- ActiveRecord::ConnectionAdapters::Quoting
- ActiveRecord::ConnectionAdapters::SQLiteAdapter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::ExplainPrettyPrinter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::Version
- ActiveRecord::ConnectionAdapters::SchemaCache
- ActiveRecord::ConnectionAdapters::SchemaStatements
- ActiveRecord::ConnectionAdapters::StatementPool
- ActiveRecord::ConnectionAdapters::Table
- ActiveRecord::ConnectionAdapters::TableDefinition
- ActiveRecord::ConnectionNotEstablished
- ActiveRecord::ConnectionTimeoutError
- ActiveRecord::CounterCache
- ActiveRecord::DangerousAttributeError
- ActiveRecord::Delegation
- ActiveRecord::DynamicFinderMatch
- ActiveRecord::DynamicMatchers
- ActiveRecord::DynamicScopeMatch
- ActiveRecord::Explain
- ActiveRecord::FinderMethods
- ActiveRecord::Fixtures
- ActiveRecord::Fixtures::File
- ActiveRecord::Generators
- ActiveRecord::Generators::Migration
- ActiveRecord::Generators::MigrationGenerator
- ActiveRecord::Generators::ModelGenerator
- ActiveRecord::Generators::ObserverGenerator
- ActiveRecord::Generators::SessionMigrationGenerator
- ActiveRecord::IdentityMap
- ActiveRecord::IdentityMap::Middleware
- ActiveRecord::Inheritance
- ActiveRecord::Inheritance::ClassMethods
- ActiveRecord::Integration
- ActiveRecord::InvalidForeignKey
- ActiveRecord::IrreversibleMigration
- ActiveRecord::Locking
- ActiveRecord::Locking::Optimistic
- ActiveRecord::Locking::Optimistic::ClassMethods
- ActiveRecord::Locking::Pessimistic
- ActiveRecord::LogSubscriber
- ActiveRecord::Migration
- ActiveRecord::Migration::CommandRecorder
- ActiveRecord::MigrationProxy
- ActiveRecord::ModelSchema
- ActiveRecord::ModelSchema::ClassMethods
- ActiveRecord::MultiparameterAssignmentErrors
- ActiveRecord::NestedAttributes
- ActiveRecord::NestedAttributes::ClassMethods
- ActiveRecord::NestedAttributes::TooManyRecords
- ActiveRecord::Observer
- ActiveRecord::Persistence
- ActiveRecord::Persistence::ClassMethods
- ActiveRecord::PreparedStatementInvalid
- ActiveRecord::QueryCache
- ActiveRecord::QueryCache::ClassMethods
- ActiveRecord::QueryMethods
- ActiveRecord::Querying
- ActiveRecord::Railtie
- ActiveRecord::Railties
- ActiveRecord::Railties::ControllerRuntime
- ActiveRecord::Railties::ControllerRuntime::ClassMethods
- ActiveRecord::ReadOnlyRecord
- ActiveRecord::ReadonlyAttributes
- ActiveRecord::ReadonlyAttributes::ClassMethods
- ActiveRecord::RecordInvalid
- ActiveRecord::RecordNotFound
- ActiveRecord::RecordNotSaved
- ActiveRecord::RecordNotUnique
- ActiveRecord::Reflection
- ActiveRecord::Reflection::ClassMethods
- ActiveRecord::Reflection::MacroReflection
- ActiveRecord::Result
- ActiveRecord::Rollback
- ActiveRecord::Sanitization
- ActiveRecord::Sanitization::ClassMethods
- ActiveRecord::Schema
- ActiveRecord::Scoping
- ActiveRecord::Scoping::ClassMethods
- ActiveRecord::Scoping::Default
- ActiveRecord::Scoping::Default::ClassMethods
- ActiveRecord::Scoping::Named
- ActiveRecord::Scoping::Named::ClassMethods
- ActiveRecord::Serialization
- ActiveRecord::SerializationTypeMismatch
- ActiveRecord::SessionStore
- ActiveRecord::SessionStore::Session
- ActiveRecord::SessionStore::SqlBypass
- ActiveRecord::SpawnMethods
- ActiveRecord::StaleObjectError
- ActiveRecord::StatementInvalid
- ActiveRecord::Store
- ActiveRecord::Store::ClassMethods
- ActiveRecord::TestFixtures
- ActiveRecord::TestFixtures::ClassMethods
- ActiveRecord::ThrowResult
- ActiveRecord::Timestamp
- ActiveRecord::Transactions
- ActiveRecord::Transactions::ClassMethods
- ActiveRecord::Translation
- ActiveRecord::UnknownAttributeError
- ActiveRecord::UnknownPrimaryKey
- ActiveRecord::Validations
- ActiveRecord::Validations::AssociatedValidator
- ActiveRecord::Validations::ClassMethods
- ActiveRecord::Validations::UniquenessValidator
- ActiveRecord::WrappedDatabaseException
- Mysql
- Mysql::Result
- Mysql::Stmt
- Mysql::Time
- ArJdbcMySQL
- ArJdbcMySQL::Error

No matching classes.

# ActiveRecord::NestedAttributes::ClassMethods

# Active Record Nested Attributes

Nested attributes allow you to save attributes on associated records through the parent. By default nested attribute updating is turned off, you can enable it using the accepts_nested_attributes_for class method. When you enable nested attributes an attribute writer is defined on the model.

The attribute writer is named after the association, which means that in the following example, two new methods are added to your model:

`author_attributes=(attributes)` and `pages_attributes=(attributes)`.

    class Book < ActiveRecord::Base
      has_one :author
      has_many :pages

      accepts_nested_attributes_for :author, :pages
    end

Note that the `:autosave` option is automatically enabled on every association that accepts_nested_attributes_for is used for.

### One-to-one

Consider a Member model that has one Avatar:

    class Member < ActiveRecord::Base
      has_one :avatar
      accepts_nested_attributes_for :avatar
    end

Enabling nested attributes on a one-to-one association allows you to create the member and avatar in one go:

    params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
    member = Member.create(params[:member])
    member.avatar.id # => 2
    member.avatar.icon # => 'smiling'

It also allows you to update the avatar through the member:

    params = { :member => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
    member.update_attributes params[:member]
    member.avatar.icon # => 'sad'

By default you will only be able to set and update attributes on the associated model. If you want to destroy the associated model through the attributes hash, you have to enable it first using the `:allow_destroy` option.

    class Member < ActiveRecord::Base
      has_one :avatar
      accepts_nested_attributes_for :avatar, :allow_destroy => true
    end

Now, when you add the `_destroy` key to the attributes hash, with a value that evaluates to `true`, you will destroy the associated model:

    member.avatar_attributes = { :id => '2', :_destroy => '1' }
    member.avatar.marked_for_destruction? # => true
    member.save
    member.reload.avatar # => nil

Note that the model will not be destroyed until the parent is saved.

### One-to-many

Consider a member that has a number of posts:

    class Member < ActiveRecord::Base
      has_many :posts
      accepts_nested_attributes_for :posts
    end

You can now set or update attributes on the associated posts through an attribute hash for a member: include the key `:posts_attributes` with an array of hashes of post attributes as a value.

For each hash that does not have an `id` key a new record will be instantiated, unless the hash also contains a `_destroy` key that evaluates to `true`.

    params = { :member => {
      :name => 'joe', :posts_attributes => [
        { :title => 'Kari, the awesome Ruby documentation browser!' },
        { :title => 'The egalitarian assumption of the modern citizen' },
        { :title => '', :_destroy => '1' } # this will be ignored
      ]
    }}

    member = Member.create(params['member'])
    member.posts.length # => 2
    member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
    member.posts.second.title # => 'The egalitarian assumption of the modern citizen'

You may also set a :reject_if proc to silently ignore any new record hashes if they fail to pass your criteria. For example, the previous example could be rewritten as:

    class Member < ActiveRecord::Base
      has_many :posts
      accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
    end

    params = { :member => {
      :name => 'joe', :posts_attributes => [
        { :title => 'Kari, the awesome Ruby documentation browser!' },
        { :title => 'The egalitarian assumption of the modern citizen' },
        { :title => '' } # this will be ignored because of the :reject_if proc
      ]
    }}

    member = Member.create(params['member'])
    member.posts.length # => 2
    member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
    member.posts.second.title # => 'The egalitarian assumption of the modern citizen'

Alternatively, :reject_if also accepts a symbol for using methods:

    class Member < ActiveRecord::Base
      has_many :posts
      accepts_nested_attributes_for :posts, :reject_if => :new_record?
    end

    class Member < ActiveRecord::Base
      has_many :posts
      accepts_nested_attributes_for :posts, :reject_if => :reject_posts

      def reject_posts(attributed)
        attributed['title'].blank?
      end
    end

If the hash contains an `id` key that matches an already associated record, the matching record will be modified:

    member.attributes = {
      :name => 'Joe',
      :posts_attributes => [
        { :id => 1, :title => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
        { :id => 2, :title => '[UPDATED] other post' }
      ]
    }

    member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
    member.posts.second.title # => '[UPDATED] other post'

By default the associated records are protected from being destroyed. If you want to destroy any of the associated records through the attributes hash, you have to enable it first using the `:allow_destroy` option. This will allow you to also use the `_destroy` key to destroy existing records:

    class Member < ActiveRecord::Base
      has_many :posts
      accepts_nested_attributes_for :posts, :allow_destroy => true
    end

    params = { :member => {
      :posts_attributes => [{ :id => '2', :_destroy => '1' }]
    }}

    member.attributes = params['member']
    member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
    member.posts.length # => 2
    member.save
    member.reload.posts.length # => 1

Nested attributes for an associated collection can also be passed in the form of a hash of hashes instead of an array of hashes:

    Member.create(:name             => 'joe',
                  :posts_attributes => { :first  => { :title => 'Foo' },
                                         :second => { :title => 'Bar' } })

has the same effect as

    Member.create(:name             => 'joe',
                  :posts_attributes => [ { :title => 'Foo' },
                                         { :title => 'Bar' } ])

The keys of the hash which is the value for `:posts_attributes` are ignored in this case. However, it is not allowed to use +'id'+ or `:id` for one of such keys, otherwise the hash will be wrapped in an array and interpreted as an attribute hash for a single post.

Passing attributes for an associated collection in the form of a hash of hashes can be used with hashes generated from HTTP/HTML parameters, where there maybe no natural way to submit an array of hashes.

### Saving

All changes to models, including the destruction of those marked for destruction, are saved and destroyed automatically and atomically when the parent model is saved. This happens inside the transaction initiated by the parents save method. See ActiveRecord::AutosaveAssociation.

### Using with attr_accessible

The use of `attr_accessible` can interfere with nested attributes if you're not careful. For example, if the `Member` model above was using `attr_accessible` like this:

    attr_accessible :name

You would need to modify it to look like this:

    attr_accessible :name, :posts_attributes

### Validating the presence of a parent model

If you want to validate that a child record is associated with a parent record, you can use `validates_presence_of` and `inverse_of` as this example illustrates:

    class Member < ActiveRecord::Base
      has_many :posts, :inverse_of => :member
      accepts_nested_attributes_for :posts
    end

    class Post < ActiveRecord::Base
      belongs_to :member, :inverse_of => :posts
      validates_presence_of :member
    end

### Constants

REJECT_ALL_BLANK_PROC

### Public Instance Methods

accepts_nested_attributes_for(*attr_names) click to toggle source

Defines an attributes writer for the specified association(s). If you are using `attr_protected` or `attr_accessible`, then you will need to add the attribute writer to the allowed list.

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. 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

  Allows you to specify that an existing record may only be updated. A new record may only be created when there is no existing record. This option only works for one-to-one associations and is ignored for collection associations. This option is off by default.

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

    # File lib/active_record/nested_attributes.rb, line 287
    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 = 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)

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

[Validate]

Generated with the Darkfish Rdoc Generator 2.