WARNING: Can't mass-assign protected attributes

浪子不回头ぞ 提交于 2019-12-31 22:42:20

问题


I get this error "WARNING: Can't mass-assign protected attributes: races_attributes" , when following this http://railscasts.com/episodes/196-nested-model-form-part-1 on rails 3.

Where Races are a component of Events. This is my models/race.rb:

class Race < ActiveRecord::Base
belongs_to :event

attr_accessible :name, :unit
end

This is my models/event.rb:

class Event < ActiveRecord::Base
has_many :races, :dependent => :destroy

accepts_nested_attributes_for :races

attr_accessible :name, :date, :description, :location_name, :address_one, :address_two, :city, :state, :zip, :active, :races_attributes
end

Any Ideas?


回答1:


attr_accessible specifies that you can not mass-assign attributes, using save method, for example. So, if you change an attribute that is not defined with attr_accessible, you will get a warning because it will not actually be saved in the database.




回答2:


Shorter than using attr_accessible, safer than using whitelist_attributes: attr_protected

Just indicate the protected attributes, and Rails will infer that all others can be mass-assigned:

class MyClass < ActiveRecord::Base
  attr_protected :id
end

(I always have way more attributes that I want mass-assigned than the ones I want protected.)



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

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