【问题标题】:Rails accepts nested attributes for multiple formsRails 接受多个表单的嵌套属性
【发布时间】:2016-09-12 09:48:44
【问题描述】:

我有两个模型,父模型和子模型。我想在使用表单创建父级时为他创建子级。我有以下内容:

父.rb

class Parent < ActiveRecord::Base
  has_many :children

  accepts_nested_attributes_for :children
end

child.rb

class Child < ActiveRecord::Base
  belongs_to :parent
end

_form.rb

<%= form_for Parent.new do |f| %>
  <%= f.label :first_name %>
  <%= f.text_field :first_name %></br>
  <%= f.label :last_name %>
  <%= f.text_field :last_name %></br>
  <%= f.label :email %>
  <%= f.text_field :email %></br>
  <%= f.label :phone %>
  <%= f.text_field :phone %></br>

  <%= f.fields_for Child.new do |builder| %>
      <%= builder.label :first_name %><br>
      <%= builder.text_field :first_name %><br>
  <% end %>

  <%= f.fields_for Child.new do |builder| %>
      <%= builder.label :first_name %><br>
      <%= builder.text_field :first_name %><br>
  <% end %>

  <%= f.submit %>


<% end %>

我希望能够在创建父级时为他创建一个或多个子级。如果我提交此表单,我会收到消息Unpermitted parameter: child

同样在我的参数哈希中,当我提交此表单时,我只获得最后一个子表单中的子信息。如何解决这个问题?

这是我的参数许可方法:

params.require(:parent).permit(:first_name, :last_name, :email, :phone, child:{})

【问题讨论】:

  • 而不是 Child.new 尝试::children 在参数中你必须过滤掉:children_attributes:{} 不是:child:{},从你的表单中查找你的参数中提交的内容rails 服务器日志。
  • 我还有'Unpermitted parameter: child'消息
  • 就像我说的,在 Rails 服务器日志中查找必须允许的参数信息。

标签: ruby-on-rails ruby forms activerecord


【解决方案1】:

您以错误的方式允许子属性,请使用:

params.require(:parent).permit(:first_name, :last_name, :email, :phone, children_attributes: [:first_name])

【讨论】:

  • 这将是复数,而不是 children_attributes,而是 childrens_attributes childrens_attributes: [:first_name]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多