完全避免大规模分配:Rails的安全性 [英] Rails security: Avoiding mass-assignment altogether
问题描述
我倾向于不用在我的生产$的大规模分配功能C $℃。 (在我的测试code,我用了很多,但在这种情况下我的执行的需要设置任意列。)
I tend to not need the mass-assignment feature in my production code. (In my test code, I use it a lot, but in those cases I do want to set arbitrary columns.)
所以,如果在我的生产code,我只是避免这些形式:
So if, in my production code, I simply avoid these forms:
Article.new(params[:article]) # or create
article.attributes = params[:article]
article.update_attributes(params[:article])
,而是始终手动枚举所有的属性,就像这样:
and instead always manually enumerate all the attributes, like so:
Article.new(:title => params[:article][:title], :body => params[:article][:body], ...)
我是挽救质量分配安全问题(即使不使用 attr_accessible
/ attr_protected
)?
编辑:的原因,我不只是禁用质量分配是,我希望能写 Article.create(:blog_id => @ blog.id,...)
,其中blog_id是一个unsave属性。
The reason I'm not just disabling mass assignment is, I'd like to be able to write Article.create!(:blog_id => @blog.id, ...)
, where blog_id is an "unsave" attribute.
推荐答案
是的,用第2种方法,你是安全的,从用户分配给其他属性。
Yes, using the 2nd method, you're safe from users assigning to other attributes.
这是一个干燥的方式来写,但:
This is a DRYer way to write it, though:
Article.new(params[:article].slice(:title, :body))
- 或 -
-or-
def article_params
params[:article].slice(:title, :body)
end
Article.new(article_params) # or create
article.attributes = article_params
article.update_attributes(article_params)
这篇关于完全避免大规模分配:Rails的安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!