简体   繁体   English

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

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

I've got a nested form (using Ryan B's nested_form gem) using a has_and_belongs_to_many to has_and_belongs_to_many setup: 我有一个嵌套的表单(使用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

When trying to add a new contact to an opening, in this case I get: 在尝试向开口添加新联系人时,在这种情况下,我得到:

Can't mass-assign protected attributes: new_1346666966632

for 对于

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

I've added the corresponding "accepts_nested_attributes_for" and "attr_accessible", and am building the contact ie @opening.contacts.build and @opening.contacts.build(params[:opening][:contact_attributes]) in the controller. 我添加了相应的“accepts_nested_attributes_for”和“attr_accessible”,并在控制器中构建了联系人,即@ opening.contacts.build和@ opening.contacts.build(params [:opening] [:contact_attributes])。

Where am I going wrong? 我哪里错了? Would it be better to use a has_many through relationship here? 在这里使用has_many通关系会更好吗?

EDIT: 编辑:

View: 视图:

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

Which uses a partial to generate fields for nested contact: 其中使用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 %>

You need to be building/creating the contacts from the opening model, as opposed to trying to assign the contacts_attributes manually. 您需要从开放模型构建/创建联系人,而不是尝试手动分配contacts_attributes。 Your controller code needs to look something like: 您的控制器代码需要看起来像:

@opening.update_attributes(params[:opening])

Check out the Rails guide for more info on using nested attributes 有关使用嵌套属性的更多信息,请查看Rails指南

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

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