Rails 4:accepted_nested_attributes_for和质量分配
我试图在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
这是我的新观点
New Person
不用说我有has_many :phones
和accepts_nested_attributes_for :phones
在我的人模型和belongs_to :person
手机模型中的人。
我有以下问题:
- 而不是3个电话号码字段,新表单中只有一个
- 当我提交表单时,我收到一个错误:
::加载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,我没有机会作为一个表单对象:(
为了在视图中获得三个手机,请将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| %>
<%= form_for :person do |f| %>
为Person
模型创建一个通用表单,并且不知道您应用于特定对象的其他详细信息(在本例中为new
操作中的@person
)。 您已将三个phones
附加到@person
对象,而@person
与@person
内容不同:person
,这就是您在视图中看不到三个电话字段的原因。 请参阅: http : //apidock.com/rails/ActionView/Helpers/FormHelper/form_for以获取更多详细信息。