Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 496
Ynv Avatar asked Nov 17 '11 22:11

Ynv


2 Answers

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.

like image 155
iain Avatar answered Nov 15 '22 07:11

iain


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

like image 28
sparrovv Avatar answered Nov 15 '22 06:11

sparrovv