【发布时间】:2023-04-01 21:05:02
【问题描述】:
我正在尝试在 Rails 4 中重现 railscast #196。但是,我遇到了一些问题。
在我的示例中,我尝试生成电话簿 - 每个人可能有多个电话号码
这些是我的控制器的重要部分:
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。
我有以下问题:
- 新表单中只有一个电话号码字段,而不是 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得到它,我就没有机会把它作为一个表单对象来做:(
【问题讨论】:
标签: ruby-on-rails object nested-forms nested-attributes