Besides the hashed password, which is saved to db, I have two
password-attributes in my User model:
attr_accessor :password, :password_confirmation
I have validations on these attributes, and I need them to work both on
create and update, since I have pages for changing and resetting the
password.
Now when I want to update just the user’s login name, I guess I have the
next options:
user = User.find(session[:user_id])
user.login = params[:login]
user.save
=> Won’t work because the password and password_confirmation validations
hit.
user = User.find(session[:user_id])
user.login = params[:login]
user.update_attributes(:login => params[:login] )
=> Won’t work because the password and password_confirmation validations
hit.
user = User.find(session[:user_id])
user.login = params[:login]
user.update_attribute(:login, params[:login] )
=> Updates the fiels to db, but passes all validations. Now I think it’s
bad idea to do the validations every time in the controller when I need
to update a field.
user = User.find(session[:user_id])
user.login = params[:login]
if user.valid?
user.update_attribute(:login, params[:login] )
end
=> Won’t work because the password and password_confirmation validations
hit.
Is there any way to skip the validations for the password attributes?
I’ve been thinkin of creating validation method in the user model, that
skips the password-fields like this:
def validate_all_but_password
loop through validations
if the validation name doesn’t equal ‘password’ or
‘password_confirmation’
run the validation
and then call it before update_attribute.
What do you think, would this be a good practise, or is there another
way to solve this problem?