用于attr_accessible/protected的Rails 3配置设置 [英] Rails 3 config setting for attr_accessible/protected
问题描述
我刚刚花了很多时间尝试解决模型中的虚拟属性问题.原来,我只是忘了将它添加到模型中的attr_accesible中.当然,我应该早点或更早就抓住它,应该首先将其添加到attr_accessible中,从而开始整个尝试.
I just spent quite some time trying to resolve a virtual attribute issue in my model. It turned out I'd simply forgotten to add it to attr_accesible in my model. Granted I should have caught it earlier or better should have started the whole endeavor by adding it to attr_accessible in the first place.
为防止这种情况再次发生,如果我尝试批量分配某些东西并在它受到保护/无法访问时对其进行验证,是否可以配置一个配置设置以引发开发异常?我知道我可以使用set config.active_record.whitelist_attributes = true
将所有列表都要求白名单,但我的问题更多是基于单个属性.
To keep this from happening again, is there a configuration setting I can flag to throw an exception on development if I try to mass assign something and validate it when it is protected/inaccessible? I know I can use set config.active_record.whitelist_attributes = true
to require whitelist for all but my question is more on an individual attribute basis.
例如,如果我有一个具有attr_accessible:name的模型,然后添加:nickname(虚拟的或非虚拟的),并尝试大量分配它以检查是否存在=> true,则上面的行不会警告我.我想警告我,我试图通过批量分配来验证受保护的属性.
The line above for example does not warn me if I have a model with attr_accessible :name then later add :nickname (virtual or not), and try to mass assign it checking for presence=>true. I want it to warn me that I tried to validate a protected attribute through mass assignment.
推荐答案
在这种情况下,Rails 3.2具有配置选项以引发ActiveModel::MassAssignmentSecurity::Error
Rails 3.2 has a configuration option to raise a ActiveModel::MassAssignmentSecurity::Error
in that case
config.active_record.mass_assignment_sanitizer = :strict
请参见 Rails 3.2发行说明和 查看全文