使用authlogic更改密码 – validation不捕获空白输入

我正在尝试创建一个表单,以允许用户更改其密码:

视图:

- 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会捕获validation错误,但在提交表单并且两个字段都为空时,Authlogic不会执行任何操作。 @ user.save必须返回true,因为我被重定向到’user_path(current_user)’。

密码实际上并未在数据库中更改。

谢谢你的帮助。

我建议你打@ 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 

我想你也应该提供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 

显然这是预期的行为。

http://www.ruby-forum.com/topic/198836

至少我现在知道了……

谢谢。

另一种方法是利用ActiveModelvalidation上下文。 您需要为User模型添加依赖于上下文的validation:

 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 

希望它能满足那些对其他建议的解决方案不满意的人。