nested form triggering a 'Can't mass-assign protected attributes warning
Asked Answered
E

1

15

I've got a multi layer nested form

User->Tasks->Prerequisites 

and in the same form

User->Tasks->Location

The location form works fine, now I'm trying to specify prerequisites to the current task. The prerequisite is a task_id stored in the :completed_task field.

When I submit the form, I get the following error in the output

WARNING: Can't mass-assign protected attributes: prerequisite_attributes

One warning for each task in the user.

I've gone through all the other questions related to this, ensuring that the field name :completed_task is being referenced correctly,

adding attr_accessible to my model (it was already there and I extended it).

I'm not sure what else i'm supposed to be doing.

My models look like

class Task < ActiveRecord::Base
     attr_accessible :user_id, :date, :description, :location_id

     belongs_to :user
     has_one :location
     accepts_nested_attributes_for :location 
     has_many :prerequisites
     accepts_nested_attributes_for :prerequisites
end

class Prerequisite < ActiveRecord::Base
     attr_accessible :completed_task

     belongs_to :task
end

the form uses formtastic, and I'm including the form via

<%= f.semantic_fields_for :prerequisites do |builder3| %>
    <%= render 'prerequisite_fields', :f=>builder3 %>
<% end %>

--- _prerequisite_fields.html.erb -----
< div class="nested-fields" >
   <%= f. inputs:completed_step %>
</div>

Any suggestions?

Elurd answered 18/2, 2011 at 3:5 Comment(1)
+1 for asking this question, I was looking for the same thing!Kimbell
I
26

Add :prerequisite_attributes to attr_accessible in order to mass-assign

attr_accessible :user_id, :date, :description, :location_id, :prerequisite_attributes

Should get you started.

Irade answered 18/2, 2011 at 3:56 Comment(2)
yup, that did it. Is this the recommended way? I didn't seem to need this in my other nested form. Previously I had added the :prerequisites_attributes to the prerequisites model, which I guess was my mistakeElurd
Yeah any time you have nested resources in your form this way, you pass the parameters as a hash of resource_attributes. This is by definition mass-assigning it, so you have to include it in attr_accessible.Irade

© 2022 - 2024 — McMap. All rights reserved.