Rails:MassAssignmentSecurity :: Error [英] Rails: MassAssignmentSecurity::Error
问题描述
遵循 ruby on rails指南,开发人员无法批量分配受保护的字段,但尝试时不会出现异常,对不对?
但是在我的情况下,通过rails
应用程序中的new
方法进行质量分配的不同参数:
Following the ruby on rails guide developer can't mass-assign protected fields but don't get exception trying to do it, right?
But in my case mass-assignment different params through new
method in rails
application:
@edition = Edition.new params[:edition]
引发以下异常:
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: price
为什么?我理解不正确吗?这是不获取批量分配例外的一种方法吗?我认为在分配之前从哈希中删除受保护的属性并不方便.
Why? Did I understand something incorrectly? Is it a way not to get the mass-assignment exception? It's not convenient to delete protected attributes from hashes before assignments i think.
更新:版本型号:
class Edition < ActiveRecord::Base
attr_accessible :title, :description
attr_protected :price
end
params[:edition].inspect
:
{"title"=>"t", "description"=>"d", "price"=>"123"}
推荐答案
您正试图通过放置
@edition = Edition.new params[:edition]
这是变量的大规模分配,根据您的编辑,在params [:edition]中,存在可变价格,根据您的代码无法进行大规模分配.
That is a mass assignment of variables and in params[:edition] according to your edit, there is the variable price which according to your code cannot be mass assigned.
要解决此问题,您必须取消我不希望这样做的价格保护,或者仅将未受保护的变量批量分配给new,然后再分配受保护的变量.因此:
To fix this you either have to remove the protection on price which I do not think you would want to do or mass-assign only the unprotected variables with new and then assign the protected variable. SO:
@edition = Edition.new params[:edition].except("price")
@edition.price = params[:edition]['price']
或@edition = Edition.new params[:edition], :without_protection => true
news.ycombinator.com/item?id=3780963 Rails 3.23现在默认情况下使验证严格,这会引发该异常.该文档已过时.
news.ycombinator.com/item?id=3780963 Rails 3.23 now makes the validation strict by default which raises that exception. The documentation is out of date.
这篇关于Rails:MassAssignmentSecurity :: Error的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!