1

我正在尝试构建一个在更新父对象时更新关联的表单。我一直在尝试使用该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 %>

我的表格用于包含多个效果记录的掌握记录。谁能明白我为什么会遇到这个错误以及我能做些什么来解决它?

4

1 回答 1

1

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

1)更改要使用的表单结构fields_for

2) 添加:effects_attributes到 Mastery 模型的 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
于 2013-02-06T17:28:59.700 回答