警告:无法批量分配受保护的属性

Hos*_*yer 10 nested-attributes ruby-on-rails-3

当在rails 3上关注此http://railscasts.com/episodes/196-nested-model-form-part-1时,我收到此错误"警告:无法批量分配受保护的属性:races_attributes" .

Races是Events的一个组成部分.这是我的模特/ race.rb:

class Race < ActiveRecord::Base
belongs_to :event

attr_accessible :name, :unit
end
Run Code Online (Sandbox Code Playgroud)

这是我的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
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Jel*_*Cat 20

比使用attr_accessible更短,比使用更安全whitelist_attributes:attr_protected

只需指出受保护的属性,Rails就会推断出所有其他属性都可以被大量分配:

class MyClass < ActiveRecord::Base
  attr_protected :id
end
Run Code Online (Sandbox Code Playgroud)

(我总是有更多的属性,我想要大量分配,而不是我想要保护的属性.)


Spy*_*ros 11

attr_accessible例如,指定您不能使用save方法批量分配属性.因此,如果更改未定义的属性attr_accessible,您将收到警告,因为它实际上不会保存在数据库中.