The problem here is that the generated form in HTML for the children are using the same "place" (same pair key/value) in the params Hash (using the params[:parent][:child][:cname]
pair). This is why there is only one param 'name' in the 'child' node in the Params hash.
To avoid that, you can use an array for the input's name:
<input type="text" name="child[][cname]" />
<input type="text" name="child[][cname]" />
The params, when this submitted, will look like this:
params: {
child: [ { cname: 'blabla' }, { cname: 'bonjour' } ]
}
To get the desired result, in your case:
<%= form_for @parent, :url => { :action => "create" } do |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 something like this:
{
"utf8"=>"✓",
"authenticity_token"=>"FQQ1KdNnxLXolfes9IGiO+aKHJaPCH+2ltDdA0TwF7w=",
"parent"=> {
"pname"=>"Heman",
"children"=> [
{ "cname"=>"SisiSenior" },
{ "cname"=>"Bonjor" },
{ "cname"=>"Blabla" }
]
},
"commit"=>"Create"}
So in your controller, you could use something like this:
#ParentsController
def create
children_attributes = params[:parent].delete(:children) # takes off the attributes of the children
@parent = Parent.create(params[:parent])
children_attributes.each do |child_attributes|
child = @parent.children.create(child_attributes)
end
end