I am trying to reproduce railscast #196 in Rails 4. However, I'm experiencing some problems.
In my example I try to generate a Phonebook - each Person could have multiple PhoneNumbers
These are important parts of my controller:
class PeopleController < ApplicationController
def new
@person = Person.new
3.times{ @person.phones.build }
end
def create
@person = Person.create(person_params)
@person.phones.build(params[:person][:phones])
redirect_to people_path
end
private
def person_params
params.require(:person).permit(:id, :name, phones_attributes: [ :id, :number ])
end
end
and this is my new view
<h1>New Person</h1>
<%= form_for :person, url: people_path do |f| %>
<p>
<%= f.label :name %> </ br>
<%= f.text_field :name %>
</p>
<%= f.fields_for :phones do |f_num| %>
<p>
<%= f_num.label :number %> </ br>
<%= f_num.text_field :number %>
</p>
<% end %>
<p>
<%= f.submit %>
</p>
<% end %>
needless to say i have has_many :phones
and accepts_nested_attributes_for :phones
in the my person model and belongs_to :person
in the phone model.
I have the following issues:
- Instead of 3 phone-number-fields there is just one in the new form
- When I submit the form I get an error:
ActiveModel::ForbiddenAttributesError
in the line
@person.phones.build(params[:person][:phones])
Parameters:
{"utf8"=>"?",
"authenticity_token"=>"l229r46mS3PCi2J1VqZ73ocMP+Ogi/yuYGUCMu7gmMw=",
"person"=>{"name"=>"the_name",
"phones"=>{"number"=>"12345"}},
"commit"=>"Save Person"}
In principle I would like to do this whole thing as a form object, but I think if I don't even get it with accepts_nested_attributes, I have no chance to do it as a form object :(
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…