繁体   English   中英

使用accepts_nested_attributes_for更新关联的问题

[英]Issues using accepts_nested_attributes_for to update associations

我正在尝试构建一种在更新父对象时更新关联的表单。 我一直在尝试使用accepts_nested_attributes_for选项以及attr_accessible但是仍然遇到Can't mass-assign protected attributes错误。

这是我的模型:

class Mastery < ActiveRecord::Base
  attr_accessible :mastery_id,
                  :name,
                  :icon,
                  :max_points,
                  :dependency,
                  :tier,
                  :position,
                  :tree,
                  :description,
                  :effects_attributes
  has_many :effects, :as => :affects, :dependent => :destroy, :order => 'effects.value'
  accepts_nested_attributes_for :effects
end


class Effect < ActiveRecord::Base
  attr_accessible :name,
                  :modifier,
                  :value,
                  :affects_id,
                  :affects_type
  belongs_to :affects, :polymorphic => true
end

这是呈现表单的部分内容:

<%= semantic_form_for [ :manage, resource ], :html => {:class => 'default-manage-form' } do |f| %>
  <%= f.inputs do %>
    <% attributes.each do |attr| %>
      <%= f.input attr.to_sym %>
    <% end %>

    <% if resource.respond_to? :effects %>
      <% resource.effects.each do |effect| %>
        <hr>
        <%= f.inputs :modifier, :name, :value, :for => effect %>
      <% end %>
    <% end %>

    <%= f.actions do %>
      <%= f.action :submit %>
    <% end %>
  <% end %>
<% end %>

我的表单用于掌握记录,其中包含多个效果记录。 谁能看到我为什么会遇到此错误以及如何解决该错误?

我通过做两件事解决了这个问题:

1)更改表单结构以使用fields_for

2)将:effects_attributes添加到精通模型的attr_accessible

这是新的表单代码:

<%= semantic_form_for [ :manage, resource ], :html => {:class => 'default-manage-form' } do |f| %>
  <%= f.inputs do %>
    <% attributes.each do |attr| %>
      <%= f.input attr.to_sym %>
    <% end %>

    <% if resource.respond_to? :effects %>
      <%= f.fields_for :effects do |b| %>
        <hr>
        <%= b.inputs :modifier, :name, :value %>
      <% end %>
    <% end %>

    <%= f.actions do %>
      <%= f.action :submit %>
    <% end %>
  <% end %>
<% end %> 

并完成模型:

class Mastery < ActiveRecord::Base
  attr_accessible :name,
                  :icon,
                  :max_points,
                  :dependency,
                  :tier,
                  :position,
                  :tree,
                  :description,
                  :effects_attributes
  has_many :effects, :as => :affects, :dependent => :destroy, :order => 'effects.value'
  accepts_nested_attributes_for :effects
end

暂无
暂无

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

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