繁体   English   中英

在Rails HABTM嵌套表单中创建新记录

[英]Creating a new record in Rails HABTM nested form

我有一个嵌套的表单(使用Ryan B的nested_form gem),使用has_and_belongs_to_many来设置has_and_belongs_to_many:

Opening has_and_belongs_to_many :contacts

Contact has_and_belongs_to_many :openings

在尝试向开口添加新联系人时,在这种情况下,我得到:

Can't mass-assign protected attributes: new_1346666966632

对于

"opening"=>{"contacts_attributes"=>{"new_1346666966632"=>{"contacts"=>{"name"=>"Test Contact",

我添加了相应的“accepts_nested_attributes_for”和“attr_accessible”,并在控制器中构建了联系人,即@ opening.contacts.build和@ opening.contacts.build(params [:opening] [:contact_attributes])。

我哪里错了? 在这里使用has_many通关系会更好吗?

编辑:

视图:

<%= simple_nested_form_for @opening, :wrapper => :plain do |f| %>
  <%= f.link_to_add "Add a contact", :contacts %>
  <%= f.button :submit %>
<% end %>

其中使用partial为嵌套联系人生成字段:

<%= f.fields_for :contacts, @opening.contacts.build do |contact_form| %>
  <%= contact_form.input :name, :label => false, :input_html => { :class => 'span6' } %>
  <%= contact_form.input :company, :label => false, :input_html => { :class => 'span6' } %>
  <%= contact_form.input :telephone, :label => false, :input_html => { :class => 'span6' } %>
  <%= contact_form.input :email_address, :label => false, :input_html => { :class => 'spa12' } %>
<% end %>

您需要从开放模型构建/创建联系人,而不是尝试手动分配contacts_attributes。 您的控制器代码需要看起来像:

@opening.update_attributes(params[:opening])

有关使用嵌套属性的更多信息,请查看Rails指南

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM