我正在尝试创建一个允许用户更改密码的表单:
查看:
- form_tag change_password_users_path do
= error_messages_for :user, :header_message => "Please Try Again", :message => "We had some problems updating your account"
%br
= label_tag :password, "New password:"
= password_field_tag "password"
%br
= label_tag :password_confirmation, "NConfirm new password:"
= password_field_tag "password_confirmation"
%br
= submit_tag "Update Account"
控制器:
def change_password
@user = current_user
if request.post?
@user.password = params[:password]
@user.password_confirmation = params[:password_confirmation]
if @user.save
redirect_to user_path(current_user)
else
render :action => "change_password"
end
end
end
Authlogic在密码“太短”或密码与确认不匹配时捕获验证错误,但在提交表单并且两个字段都为空时不执行任何操作。 @ user.save必须返回true,因为我被重定向到'user_path(current_user)'。
密码实际上并未在数据库中更改。
感谢您的帮助。
答案 0 :(得分:2)
我认为你还应该提供params [:user] [:current_password],否则你无法保存@user。当我测试时,我发现更改密码后current_user将丢失,因此您需要更新usersession。
为您的用户模型添加'current_password'访问者
class User < ActiveRecord::Base
act_as_authentic
attr_accessor :current_password
end
在用户控制器中
def change_password
@user = current_user
if @user.valid_password? params[:user][:current_password]
@user.password = params[:user][:password]
@user.password_confirmation = params[:user][:password_confirmation]
if @user.changed? && @user.save
UserSession.create(:login => @user.login, :password => params[:user][:password])
redirect_to user_path(current_user)
else
render :action => "change_password"
end
end
end
答案 1 :(得分:1)
答案 2 :(得分:1)
我建议你像以下示例一样调用 @ user.changed?来检查空白密码:
def change_password
@user = current_user
if request.post?
@user.password = params[:user][:password]
@user.password_confirmation = params[:user][:password_confirmation]
if @user.changed? && @user.save
redirect_to user_path(current_user)
else
render :action => "change_password"
end
end
end
答案 3 :(得分:0)
另一种方法是利用ActiveModel验证上下文。您需要向用户模型添加依赖于上下文的验证:
validates :password, # :password_confirmation,
:presence => {:message => 'Please enter your new password.'},
:on => :reset_password
然后,在控制器中它将只是:
def change_password
@user = current_user
if request.post?
@user.password = params[:password]
@user.password_confirmation = params[:password_confirmation]
if @user.save(:context => :reset_password)
redirect_to user_path(current_user)
else
render :action => "change_password"
end
end
end
希望能够帮助那些对其他建议的解决方案不满意的人。