【问题标题】:Rails 4: accepts_nested_attributes_for and mass assignmentRails 4:accepts_nested_attributes_for 和批量赋值
【发布时间】: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 :phonesaccepts_nested_attributes_for :phones,手机模型中有 belongs_to :person

我有以下问题:

  1. 新表单中只有一个电话号码字段,而不是 3 个电话号码字段
  2. 提交表单时出现错误:

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


    【解决方案1】:

    为了在视图中获得三个电话,请将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
    

    更新:

    &lt;%= form_for :person do |f| %&gt;Person 模型创建一个通用表单,并且不知道您应用于特定对象的其他详细信息(在这种情况下,@person 在您的new 操作中)。您已将三个phones 附加到@person 对象,而@person:person 不同,这就是您没有在视图中看到三个电话字段的原因。详情请参考:http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for

    【讨论】:

    • 耶!这解决了这两个问题 - 不能说我有多高兴!在基本的 Rails 教程中,他们使用哈希:guides.rubyonrails.org/getting_started.html#the-first-form - 你能详细说明区别吗?
    • @speendo,如果您的意思是使用符号与使用对象之间的区别,请查看更新。
    • 我有后续评论。如果手机型号有phone_type_id,并且code def new @person = Person.new ph = Person.phone.build ph[:phone_type_id] = 1 ph2 = Person.phone.build ph2[:phone_type_id] = 2 end @ 987654338@视图如何知道手机类型id并在新方法结束时不保存code@personcode而将其发回?
    • 这很好用,但是缺少一些东西。当由于某种原因输入无效并且无法创建person 时,按照@speendo 所说的相同指南,我们执行render 'new' 并且phones(或在我的情况下为emails)的字段消失了。跨度>
    • @unmultimedio,您还需要确保在调用render 'new'之前建立任何必要的关联。
    猜你喜欢
    • 2012-08-17
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多