我正在尝试在Rails 4中重现railscast #196。但是,我遇到了一些问题。

在我的示例中,我尝试生成一个电话簿-每个人可以有多个电话号码

这些是 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

这是我的新观点
<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 :phonesaccepts_nested_attributes_for :phones,电话模型中有belongs_to :person

我有以下问题:
  • 而不是3个电话号码字段,只有一种新形式
  • 提交表单时出现错误:



  • 在行中
    @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来做到这一点,我就没有机会将它作为表单对象来做::(

    最佳答案

    为了在 View 中获得三部手机,将form_for :person更改为form_for @person(您要使用此处构建的对象),如下所示:

    <%= form_for @person, url: people_path do |f| %>
    

    这也应该修复ForbiddenAttributes错误。

    您的create Action 可能是:
    def create
        @person = Person.create(person_params)
    
        redirect_to people_path
    end
    

    更新:
    <%= form_for :person do |f| %>Person模型创建通用形式,并且不知道您应用于特定对象的其他详细信息(在本例中为@person操作中的new)。您已经在phones对象上附加了三个@person,并且@person:person不同,这就是为什么您在 View 中没有看到三个电话字段的原因。请引用:http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for了解更多详细信息。

    10-07 19:04
    查看更多