views:

30

answers:

2

In rails, when updating a model, how do you prevent certain properties of the model from being updated when using a call like:

@user.update_profile params[:user]

Since anyone can just create a form input with a name like 'password', how can you filter the set of properties that you are allowing to be updatable?

Is this what attr_XXX is for?

+4  A: 

You're looking for attr_accessible. It lets you specify which attributes can be set through mass-updating (like update_attributes), but you'll still be able to set the attributes "manually" (ie @user.attribute = ...).

For more information, see The importance of attr_accessible in Ruby on Rails.

Daniel Vandersluis
ok so that will prevent mass updates during form posts etc. right?
Blankman
@Blankman Correct, any attributes that are not specified as accessible will not be updateable through `params`.
Daniel Vandersluis
+3  A: 

You're looking for attr_protected to black list any attributes you don't want altered in a bulk update. Throw it in your model and give it a list of attribute symbols to blacklist.

class User < ActiveRecord::Base
  attr_protected :password
end 

Alternatively you can use attr_accessible to take the white list approach and only the attributes given can be updated when updating the entire record at once. Every other attribute will be protected.

N.B Protected attributes can still be overwritten if it's directly assigned to as in

@user.password = "not secure"
EmFi
Note that `attr_protected` and `attr_accessible` (which I mentioned in my answer), are two sides of the same coin. `attr_accessible` makes you list the attributes you **want** to have bulk updateable; `attr_protected` lists the attributes you **don't want** to be updateable.
Daniel Vandersluis
However, with `attr_accessible`, if you ever add more attributes to your model, you won't have to worry about them being accessible unless you specify them as such; with `attr_protected`, any new attributes will be accessible. Of course, which is the right answer depends on what you expect to happen (though some people think it's preferable to explicitly list what you do want so that there aren't any surprises).
Daniel Vandersluis
@Daniel Vandersluis: Yes That's true. White listing with attr_accessible is a much better security strategy than black listing with attr_protected. But the way the question was worded implied the black list approach was preferred.
EmFi