Why use "accepts_nested_attributes_for" when you can already save through the parent?
When should I use "accepts_nested_attributes_for"? In the example below, I can d开发者_运维问答o a successful "user.microposts.create" without needing "accepts_nested_attributes_for" in the User model.
class Micropost < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :microposts
end
accepts_nested_attributes_for
is just a shortcut. It defines a dynamic attribute {field_name}_attributes
so that if you have a form you can include nested attributes and have it automatically assign them to an association. Like so :
form_for :object do |f|
f.text_field :attr1
f.text_field :attr2
f.fields_for :association_attributes do |g|
g.text_field :nested1
g.text_field :nested2
end
end
This posts with parameters {object: {attr1: val, attr2: val, association_attributes: {nested1: val, nested2: val}}
and adding accepts_nested_attributes_for :association
to your class makes the whole thing work without any extra code.
精彩评论