开发者

Is it possible to limit which fields get persisted?

开发者 https://www.devze.com 2023-01-23 14:06 出处:网络
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 wit

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:

  1. Passwords should be stored using a one-way hash, and so passwords should not be 'decryptable'
  2. 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 called password_salt.
  3. password_confirmation is a virtual attribute and does not need to be defined in the model (rails will manage the details internally)
0

精彩评论

暂无评论...
验证码 换一张
取 消