2011-03-24 29 views
3

我倾向于不需要生产代码中的mass-assignment功能。 (在我的测试代码,我用了很多,但在这种情况下我要设置任意列。)Rails安全性:完全避免大规模分配

所以,如果在我的生产代码,我只是避免这些形式:

Article.new(params[:article]) # or create 
article.attributes = params[:article] 
article.update_attributes(params[:article]) 

,而总是手动枚举所有的属性,就像这样:

Article.new(:title => params[:article][:title], :body => params[:article][:body], ...) 

我是从质量分配安全问题保存(即使不使用attr_accessible/attr_protected)?

编辑:我不只是禁用批量分配的原因是,我希望能写Article.create!(:blog_id => @blog.id, ...),其中blog_id是一个“unsave”属性。

回答

10

是,采用第2种方法,你是从用户分配给其他属性的安全。

这是一个干燥的方式写出来,虽然:

Article.new(params[:article].slice(:title, :body)) 

- 或 -

def article_params 
    params[:article].slice(:title, :body) 
end 

Article.new(article_params) # or create 
article.attributes = article_params 
article.update_attributes(article_params) 
2

config/environments/production.rb末尾添加这样的:

ActiveRecord::Base.send(:attr_accessible, nil) 
+0

但是我不想这样做,因为我希望能够纠正ite'User.create!(:name =>'J. R. Hacker',:admin => true)'在我的测试代码中。我的问题是,如果我不全局禁用群发任务,我还能保存吗? – 2011-03-24 20:04:28

+2

以上只适用于您的产品代码,而不是您的测试代码 – Zabba 2011-03-24 20:05:16

+0

啊,当然是。但问题在于:如果我这样做,我必须写'a = Article.new; a.blog_id = blog.id; ...; a.save!'。我宁愿写'Article.create!(blog_id => blog.id,...)' - 但我只能这样做,如果我离开质量分配打开,即使在不安全的属性,如blog_id。所以我想知道这是否是一件可以保存的事情(只要我避免传入被感染的哈希)。 – 2011-03-24 20:11:48

0

我无法获取多个参数约翰Douthat的方法工作,所以我想出了以下替代方案(取自我的CommentsController):

def set_params 
    @comment.parent_id = params[:blog_comment][:parent_id] 
    @comment.ip_address = request.remote_ip 
    @comment.commentator = current_user.username || "anonymous" 
    @comment.name = params[:blog_comment][:name] 
    @comment.email = params[:blog_comment][:email] 
    @comment.url = params[:blog_comment][:url] 
end 

def create 
    @comment = @post.comments.build(params[:blog_comment]) 
    set_params 

    if @comment.save 
    ... 
end 

def update 
    @comment = Blog::Comment.find(params[:id]) 
    set_params 

    if @comment.update_attributes(params[:blog_comment]) 
    ... 
end