User model saves with blank password

已查看 61 次
跳至第一个未读帖子

Murkyl

未读,
2009年2月1日 21:30:322009/2/1
收件人 Authlogic
I'm new to RAILS so if I'm not understanding something please let me
know.

I'm trying to do this:

@user = @current_user;
unless @user.valid_password?(params[:old_password])
render :action => :edit, :id => params[:id], :login => params
[:login];
return;
end

@user.password = params[:password];
@user.password_confirmation = params[:password_confirmation];
if (@user.save)
redirect_to(root_path);
else
render :action => :edit, :id => params[:id], :login => params
[:login];
return;
end

To change a user's password. The old password validation works fine
but if the password and password_confirmation fields are left empty,
the @user model saves correctly. The password isn't updated but the
model returns true. I would expect the model to return false since
the validations should be running. If I put any character into the
password or password confirmation then the length validations will run
and so will the validates_confirmation_of constraint.

What am I doing wrong?

Ben Johnson

未读,
2009年2月3日 23:47:552009/2/3
收件人 Authlogic
Hi,

You aren't doing anything wrong. Authlogic ignores blank passwords.
This really is an application specific issue. Some people like to have
1 form where the user can change their details as well as their
password, but leaving the password blank would just ignore a password
change. In your instance the user is explicitly trying to change the
password, and you want validation to occur no matter what in this
action. You don't want the password being validated on every save
because the password is a virtual field and thus would need to be
supplied every time you want to save a user object.

So what I did was add a validate_password attribute. Just pass true to
this and the object will be validated using the password validations.
So your action will look something like:

@user.validate_password = true
...

Just update from the repo and you should be good.
回复全部
回复作者
转发
0 个新帖子