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

时间:2012-09-03 10:16:43

标签: ruby-on-rails ruby-on-rails-3 nested-forms nested-attributes has-and-belongs-to-many

我有一个嵌套表单(使用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 %>

使用部分生成嵌套联系人的字段:

<%= 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 %>

1 个答案:

答案 0 :(得分:2)

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

@opening.update_attributes(params[:opening])

查看Rails guide for more info on using nested attributes