我正在尝试构建一个表单,在更新父对象时更新关联。我一直在尝试使用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 %>
我的表格是Mastery记录,其中包含多个Effect记录。有人知道我为什么会遇到这个错误吗?我能做些什么来修复它吗?
我通过做两件事解决了这个问题:
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