Reputation: 2585
I'm trying to build a form that updates an association when updating the parent object. I've been trying to use the accepts_nested_attributes_for
option as well as attr_accessible
but am still running into a Can't mass-assign protected attributes
error.
Here are my models:
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
Here's the partial that's rendering the form:
<%= 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 %>
My form is for the Mastery record which contains multiple Effect records. Can anyone see why I'd be running into this error and what I can do to fix it?
Upvotes: 1
Views: 308
Reputation: 2585
I've resolved this by doing two things:
1) Changing the form structure to use fields_for
and
2) Adding :effects_attributes
to the attr_accessible for the Mastery model
Here's the new form code:
<%= 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 %>
And finished model:
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
Upvotes: 1