In my update user profile form, the first field asks the user to enter her current password. When she submits the form, I verify the password before accepting the changes in other fields. Here's how I'm currently doing this in the users controller:
def update
@user = User.find(params[:id])
if @user.has_password?(params[:user][:password])
if @user.update_attributes(params[:user])
flash[:success] = "Profile updated."
re开发者_如何学编程direct_to @user
else
render 'edit'
end
else
flash[:failure] = "Password does not match!"
render 'edit'
end
end
I feel like there's a better way to do this. For instance I could make password matching a validation in the user model. Then formtastic would automatically handle the error message for me (as opposed to my ugly flash approach above). I tried doing this with
validate :password_match?, :on => :update
And
def password_match?
has_password(params[:user][:password])
end
But as suspected params is not accessible from the model.
I searched SO for 20 minutes for a way to do this, couldn't find anything that did not involve Devise or Authlogic. I'm doing authentication from scratch (everything works fine: signin, sessions, etc.).
Please, show me the light on the better way!
You don't need devise, just use a before filter on your controller on update On your profile controller.
before_filter password_match, :only => :update
then on the bottom as private.
private
def password_match
@user = User.find(params[:id])
@user.has_password?(params[:user][:password])
精彩评论