Ruby on Rails creating multiple children in one parent form -
i have parent has multiple children. want when submit form, parent generated in parent model, , multiple records created in child model, 1 each child. when try , submit, following error:
activerecord::associationtypemismatch in parentscontroller#create child(#) expected, got array(#)
when uncomment accepts_nested_attributes_for :children , change f.fields_for :children f.fields_for :children_attributes, different error:
typeerror in parentscontroller#create can't convert symbol integer
i @ loss do. have checked out nested model forms railscasts, dealing generating children fields inside form, , learned railscasts didn't seem work. pretty doing builder.text_field :cname's in form wrong, i'm not aware of proper way it.
my code:
parent.rb
class parent < activerecord::base has_many :children #accepts_nested_attributes_for :children attr_protected :id
child.rb
class child < activerecord::base belongs_to :parent attr_protected :id
_form.html.erb
<%= form_for @parent, :url => { :action => "create" } |f| %> <%= f.text_field :pname %> <%= f.fields_for :children |builder| %> <%= builder.text_field :cname %> <%= builder.text_field :cname %> <%= builder.text_field :cname %> <% end %> <%= f.submit %> <% end %>
params content:
{"utf8"=>"✓", "authenticity_token"=>"fqq1kdnnxlxolfes9igio+akhjapch+2ltdda0twf7w=", "parent"=>{"pname"=>"heman", "child"=>{"cname"=>""}}, "commit"=>"create"}
the problem here is generated form in html children using same "place" (same pair key/value) in params hash (using params[:parent][:child][:cname]
pair). why there 1 param 'name' in 'child' node in params hash.
to avoid that, can use array input's name:
<input type="text" name="child[][cname]" /> <input type="text" name="child[][cname]" />
the params, when submitted, this:
params: { child: [ { cname: 'blabla' }, { cname: 'bonjour' } ] }
to desired result, in case:
<%= form_for @parent, :url => { :action => "create" } |f| %> <%= f.text_field :pname %> <%= text_field_tag "parent[children][][cname]" %> <%= text_field_tag "parent[children][][cname]" %> <%= text_field_tag "parent[children][][cname]" %> <%= f.submit %> <% end %>
should produce this:
{ "utf8"=>"✓", "authenticity_token"=>"fqq1kdnnxlxolfes9igio+akhjapch+2ltdda0twf7w=", "parent"=> { "pname"=>"heman", "children"=> [ { "cname"=>"sisisenior" }, { "cname"=>"bonjor" }, { "cname"=>"blabla" } ] }, "commit"=>"create"}
so in controller, use this:
#parentscontroller def create children_attributes = params[:parent].delete(:children) # takes off attributes of children @parent = parent.create(params[:parent]) children_attributes.each |child_attributes| child = @parent.children.create(child_attributes) end end
Comments
Post a Comment