Rails 4 - saving object with nested attributes -
i have parent model has 1 child model nested attributes. have single form updates both parent , child.
here models:
class parent < activerecord::base has_one :child accepts_nested_attributes_for :child end class child < activerecord::base belongs_to :parent end
form view:
<%= form_for @parent, |f| %> <%= f.text_field :parent_name %> <%= f.fields_for @parent.child |c| %> <%= c.text_field :child_name %> <% end %> <%= f.submit "save" %> <% end %>
parent controller:
class parentscontroller < applicationcontroller def update @parent = parent.find(params[:id]) @parent.update(params.require(:parent).permit(:parent_name, child_attributes: [:child_name])) redirect_to @parent end end
when save form, parent updates child doesn't. doing wrong?
you have problem in nested part of form code, should be
<%= form_for @parent, |f| %> <%= f.text_field :parent_name %> <%= f.fields_for :child |c| %> <<<<<<<<<<< line wrong <%= c.text_field :child_name %> <% end %> <%= f.submit "save" %> <% end %>
you have pass id in params attributes :
@parent.update(params.require(:parent).permit(:parent_name, child_attributes: [:id, :child_name]))
cheers
Comments
Post a Comment