Carla Dessi
Carla Dessi

Reputation: 9686

Nested Form, "Can't mass-assign protected attributes"

This is the relevant part of my nested form:

<div class="field">
<%= f.fields_for "@partcode" do |p|%> 

  <%= p.label "partcode"%><br />
  <%= p.text_field :partcode %>

<% end %>
</div>

and i already have this in my model:

attr_accessible :partcode,
                :description

yet when i enter something in to the form, i get this error:

Can't mass-assign protected attributes: @partcode

Here is my partcode model:

class Partcode < ActiveRecord::Base
 attr_accessible :partcode,
              :description

  validates       :partcode,
              :description,
              :presence => true

 belongs_to "goods_ins"

 accepts_nested_attributes_for "goods_ins"


end

and here is all the code from my goods in model:

class GoodsIn < ActiveRecord::Base
  attr_accessible :c4lpono, 
              :courier, 
              :deliverydate,  
              :deliverynoteno,  
              :description,  
              :destination,  
              :notes,  
              :partcode,  
              :quantity,  
              :signedby,  
              :suppliername

  validates       :deliverydate,  
              :deliverynoteno,  

              :destination,

              :quantity,  
              :signedby,  
              :suppliername,
              :presence => true

 has_many :suppliers

 has_many :partcodes

 accepts_nested_attributes_for :partcodes
end

Also here is the new part of my partcode controller:

def new
@partcode = Partcode.new

respond_to do |format|
  format.html # new.html.erb
  format.json { render :json => @partcode }
end
end 

Upvotes: 3

Views: 2460

Answers (4)

Draiken
Draiken

Reputation: 3815

Your model has to have accepts_nested_attributes_for :partcode or it won't accept it's attributes.

Also Partcode class has to have his attributes white listed too.

UPDATE:

The @partcode must have a new Partcode in it. Make sure you set @partcode = @goods_in.partcodes.build or a simple @partcode = Partcode.new.

The fields for on the form should be like this <%= f.fields_for @partcode do |p| %>, without the quotes too.

Upvotes: 0

Hishalv
Hishalv

Reputation: 3052

Should'nt you have :partcode_attributes to attr_accessible(in GoodsIn Model), like this:

attr_accessible :partcode_attributes

Assuming your model association is configured that way. hope it helps

Upvotes: 7

MurifoX
MurifoX

Reputation: 15109

Looking at the comments from your answer i believe you can use the build method made for has_one relanshionships:

@partcode = GoodsIn.build_partcode

SO your form can be like this:

<%= f.fields_for @partcode do |p|%> 

Upvotes: 0

Trip
Trip

Reputation: 27124

I'd like to look at your model. But attr_accessible isn't an instance. I think it should just say this

<%= f.fields_for "partcode" do |p|%>` 

than in your controller :

@partcode = Partcode.new(params["partcode"])

Upvotes: 0

Related Questions