Can't mass-assign protected attributes

落花浮王杯 提交于 2019-12-20 16:22:48

问题


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"=>"a2@gmail.com", "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 'a2@gmail.com') 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


回答1:


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




回答2:


Inside of SpecificModel (appfolder/app/model/specific_model.rb)

Try using

attr_accessible :addresses_attributes, :another_attribute_to_make_mass_assignable, :another_attribute, etc.




回答3:


Nowadays (April 2013) you should start to use https://github.com/rails/strong_parameters




回答4:


Just include the datafield in the model as mentioned below

attr_accessible :addresses_attributes


来源:https://stackoverflow.com/questions/6163759/cant-mass-assign-protected-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!