I also posted this on railsforum but then I realized this is probably not the best place to get answers for this problem. So, sorry for this crosspost…
I also want to apologize for this long message. I just wanted to provide all information - on the one hand to make the error reproducable, on the other hand to enable people who maybe have the same problem in the future to get step-by-step instructions.
I try to generate a form with an 1:many-model. Doing so, I found the command accepts_nested_attributes_for. However, in my form only the parent-model gets saved, while the child-model stays empty.
I started by creating a project (I called it PhoneBook) in Rails 4.
Then I generated two models and started the migration:
$ rails g model person name
$ rails g model phone person_id:integer phone_number:integer
$ rake db:migrate
== CreatePeople: migrating ===================================================
== CreatePeople: migrated (0.0008s) ==========================================
== CreatePhones: migrating ===================================================
== CreatePhones: migrated (0.0008s) ==========================================
Next, I specified the models
class Person < ActiveRecord::Base
class Phone < ActiveRecord::Base
Then I created a controller for person
$ rails g controller people
This controller was filled with the following code
class PeopleController < ApplicationController
@person = Person.new
@person = Person.new(person_params)
@person = Person.all
params.require(:person).permit(:name, phone_attributes: [ :id, :phone_number ])
Of course I also needed some views. This one just shows the list of all people with their phone numbers
<%= person.name %>
<ul> <% person.phones.each do |phone| %> <li> <%= phone.phone_number %> </li> <% end %> </ul> </li>
<% end %>
<% @person.each do |person| %>
and this one is the interesting part: here’s my code for the form that should create new people and phone numbers:
<%= form_for :person, url: people_path do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.fields_for :phones do |f_phone| %>
<%= f_phone.label :phone_number %>
<%= f_phone.text_field :phone_number %>
<% end %>
<%= f.submit %><% end %>
To make it work (well it doesn’t work, but almost) I also need a route of course:
Are you still with me? Great! Creating a new person with a phone number in the rails console works without any problems. However, when I try my form, only the Person gets stored, while the phone number is lost.
Can you help me with this problem? What am I doing wrong?
Do I maybe need a controller for phone_number? As it is only accessed via person, I thought I wouldn’t need one.
Thank you in advance!