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

Chr*_*rds 5 ruby-on-rails nested-forms has-and-belongs-to-many nested-attributes ruby-on-rails-3

我有一个嵌套的表单(使用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 %>
Run Code Online (Sandbox Code Playgroud)

其中使用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 %>
Run Code Online (Sandbox Code Playgroud)

Pet*_*own 2

您需要从打开的模型构建/创建联系人,而不是尝试手动分配contacts_attributes。您的控制器代码需要类似于:

@opening.update_attributes(params[:opening])
Run Code Online (Sandbox Code Playgroud)

查看Rails 指南以获取有关使用嵌套属性的更多信息