Blankman
Blankman

Reputation: 266920

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?

Upvotes: 5

Views: 862

Answers (2)

EmFi
EmFi

Reputation: 23450

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"

Upvotes: 4

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94123

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.

Upvotes: 6

Related Questions