Updating select attributes on a profile page


#1

Thanks ahead of time for everyone who will help out with this.

I have a profile page for a blog engine I’m writing (because everyone
much write a blog engine at some point to learn stuff) and I want to
allow members the ability to update their passwords. What I’m having a
problem with right now is using the edit page for their profile to
update their email and name (which is already populated from the
database), which works, but also use it to update the password (which
does not … because it updates the password to blank every time).

The situation is this: I am both salting and hashing the password, and
using the attr_accessor to grab the password they input on the
registration page. However, now when they update their profile, the
blank password field generates a new hash and salt and leaves the
password blank. Not ideal.

I’m wondering how I might be able to selectively update the password
if a new password is supplied … but leave it alone if a password is
not supplied.

Any help is greatly appreciated!


#2

I did a really kludgy fix last night using attr_protected, and I like
certain aspects of your idea as well. If I find some time tonight I’ll
probably take a look at the code again to try and work out a more
“beautiful” option for myself. :slight_smile:

Thanks for your help!


#3

I use some code like this:

attr_accessor :new_password

validates_presence_of :new_password, :on => :create
validates_length_of :new_password, :minimum => 6, :allow_nil =>
true, :allow_blank => true, :unless => :new_password.blank?
validates_confirmation_of :new_password

before_save :set_encrypted_password

def set_encrypted_password
write_attribute(:password, Client.encrypt_password(@new_password))
unless @new_password.nil? || @new_password.blank?
end

def self.encrypt_password(password)
Digest::SHA1.hexdigest(“something_random_goes_here_#{password}”)
end

def self.authenticate(email, password)
find_by_email_and_password_and_active(email, encrypt_password
(password), true)
end