Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent certain properties from being updated?

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?

like image 230
Blankman Avatar asked Oct 06 '10 02:10

Blankman


2 Answers

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.

like image 117
Daniel Vandersluis Avatar answered Oct 17 '22 12:10

Daniel Vandersluis


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"
like image 29
EmFi Avatar answered Oct 17 '22 13:10

EmFi