What could happen if I use :without_protection=>true when creating a new model in rails 3.1?

北城余情 提交于 2019-12-09 13:11:18

问题


I have encountered a problem in my application and realized that I could fix it by setting :without_protection => true when creating a model, e.g.:

Model.new(params[:model], :without_protection => true). 

What exactly is rails protecting the models from? Thanks!


回答1:


It's protection against unintended mass assignment.

The problem with the code you shown is that users can alter the form and change attributes you don't want them to change, like hashed passwords on users or a published status on posts.

You can use attr_protected and attr_accessible on models to protect attributes on your models to be overridden. When an attribute is protected than the value from params will be ignored (a notice will appear in your log).

class Model < ActiveRecord::Base
  attr_accessible :one, :two
end

Before Rails 3.1, that was it. There was no way to configure it afterwards. Now, with Rails 3.1, you can assign roles:

class Model < ActiveRecord::Base
  attr_accessible :one, :two, :as => :admin
  attr_accessible :one, :as => :regular_user
end

And specify it when doing mass updates (new or update_attributes):

Model.new(params[:model], :as => :regular_user)

Using :without_protection, will make every attribute free to be mass assigned and should be used VERY sparingly. Never use when you're passing in user data. You might use it in db/seeds.rb for example.




回答2:


This protects you against mass assignment.

Assume that, your model looks something like that:

class CreditCard
  belongs_to :user
end

You wouldn't like that someone will call your update action on creditcards_controller and pass another user_id attribute in params[:credit_card]

You can read more about mass assignment security here



来源:https://stackoverflow.com/questions/8175035/what-could-happen-if-i-use-without-protection-true-when-creating-a-new-model-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!