我正在尝试在Rails 4中重现railscast #196。但是,我遇到了一些问题。
在我的示例中,我尝试生成一个电话簿 - 每个人可以拥有多个PhoneNumbers
这些是我的控制器的重要部分:
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
这是我的新观点
<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 %>
不用说我的人物型号中有has_many :phones
和accepts_nested_attributes_for :phones
,手机型号中有belongs_to :person
。
我有以下问题:
::加载ActiveModel ForbiddenAttributesError
在
行@person.phones.build(params[:person][:phones])
参数:
{"utf8"=>"✓",
"authenticity_token"=>"l229r46mS3PCi2J1VqZ73ocMP+Ogi/yuYGUCMu7gmMw=",
"person"=>{"name"=>"the_name",
"phones"=>{"number"=>"12345"}},
"commit"=>"Save Person"}
原则上我想把这整件作为一个表单对象,但我想如果我甚至没有使用accepts_nested_attributes,我就没有机会将它作为一个表单对象:(
答案 0 :(得分:12)
为了在视图中将三部手机更改为form_for :person
至form_for @person
(您希望使用此处构建的对象),如下所示:
<%= form_for @person, url: people_path do |f| %>
这也应该解决ForbiddenAttributes
错误。
您的create
行动可能是:
def create
@person = Person.create(person_params)
redirect_to people_path
end
<强>更新强>
<%= form_for :person do |f| %>
为Person
模型创建了一个通用表单,并且不知道您应用于特定对象的其他详细信息(在这种情况下@person
new
行动)。您已将三个phones
附加到@person
对象,而@person
与:person
不同,这就是您在视图中看不到三个电话字段的原因。有关详细信息,请参阅:http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for。