【问题标题】:Creating a new record in Rails HABTM nested form在 Rails HABTM 嵌套表单中创建新记录
【发布时间】:2012-09-03 10:16:42
【问题描述】:

我有一个嵌套表单(使用 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 through 关系会更好吗?

编辑:

查看:

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

【问题讨论】:

  • 尝试添加 attr_accessible :contacts_attributes 并检查
  • 对不起,忘了说我也有这个
  • 如果显示 mass-assign 错误,则需要检查 attr_accessible 代码是否为复数 (:contacts_attributes). Also, in your view: `

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


【解决方案1】:

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

@opening.update_attributes(params[:opening])

查看Rails guide for more info on using nested attributes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多