Is it possible to limit which fields get persisted?
I've got a User model that is utilizing mongoid. The model has a password, password_confirmation and encrypted_password field. The password and password_confirmation fields are populated at runtime with the value the user would type on the screen when creating a new user. When I persist, I don't want to persist the开发者_如何学运维 unencrypted password values, I only want to persist the value contained in encrypted_password. Is this possible? Is there something I can use to denote certain fields as not being persistable?
Thanks in advance
Chris
Here's a way:
Model only needs the password field and use a before_filter:
def User
before_save :hash_password
attr_accessible :password, :password_confirmation
def hash_password
#todo: improve by adding a salt
self.password = Digest::SHA1.hexdigest(self.password)
end
end
Notes:
- Passwords should be stored using a one-way hash, and so passwords should not be 'decryptable'
- Use a salt (a random value) and add that to the password before passing it to the
hexdigest()
. Store the salt in the database as well - say a column calledpassword_salt
. password_confirmation
is a virtual attribute and does not need to be defined in the model (rails will manage the details internally)
精彩评论