Can't mass-assign protected attributes

Sanjay picture Sanjay · May 28, 2011 · Viewed 62.4k times · Source

Updating the code formatting for better viewing.

Folks,

I have been looking at this for sometime but I don't understand what could be messing up here. I am using Devise.

class User < ActiveRecord::Base
  has_many :addresses
  accepts_nested_attributes_for :addresses

  # Other stuff here
end

class Address < ActiveRecord::Base

  belongs_to :user

  validates_presence_of :zip #:street_address1, 

end

-------------------- log output begin ------------------------------

Started POST "/users" for 127.0.0.1 at 2011-05-28 11:43:27 -0700 Processing by RegistrationsController#create as HTML Parameters: {"utf8"=>"√", "authenticity_token"=>"CEmdqlsmdYa6Jq0iIf5KAxxISsUCREIrFNXWkP80nhk=", "user"=>{"email"=>"[email protected]", "password"=>"[FILT ERED]", "addresses_attributes"=>{"0"=>{"street_address1"=>"234 Pitkin Ct.", "zip"=>"12456"}}}, "commit"=>"Sign up"} WARNING: Can't mass-assign protected attributes: addresses_attributes SQL (0.0ms) BEGIN SQL (164.0ms) SHOW TABLES
User Load (0.0ms) SELECT users.id FROM users WHERE (users.email = BINARY '[email protected]') LIMIT 1 SQL (1.0ms) ROLLBACK

-------------------- log output end ------------------------------

The zip is present in the data posted and the posted data seems to be formatted properly. On the web page form I am getting the error that "Addresses zip can't be blank". I have dug around for what causes the "Can't mass-assign protected attributes" warning but haven't found anything that will help me.

Thanks for your thoughts and pointers.

-S

Answer

apneadiving picture apneadiving · May 28, 2011

Have a look here and learn :)

http://railscasts.com/episodes/26-hackers-love-mass-assignment


Edit:

Having accepts_nested_attributes_forin User model enables you to send the data to the Address model.

Then, in the Address model, you have to set the requested attr_accessible