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

I ran into a problem in my application and realized that I could fix it by setting :without_protection => true when creating the model, for example:

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

What are rails protecting models? Thanks!

+6
source share
2 answers

Protection against unintentional mass misappropriation.

The problem with the code you showed is that users can change the form and change attributes that you do not want to change, for example, hashed user passwords or published status in messages.

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

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

Before Rails 3.1, that’s it. After that, there was no way to configure it. 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 in bulk updates ( new or update_attributes ):

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

Using :without_protection , each attribute will be free for mass assignment and should be used VERY sparingly. Never use when you transfer user data. You can use it in db/seeds.rb , for example.

+16
source

This protects you from mass appropriation.

Suppose your model looks something like this:

 class CreditCard belongs_to :user end 

You won’t like someone calling your update action on creditcards_controller and passing another user_id attribute in the [: credit_card] parameters

You can learn more about mass assignment security here.

+1
source

Source: https://habr.com/ru/post/901757/


All Articles