4

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

看法:

- 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)'。

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

谢谢你的帮助。

4

4 回答 4

3

我认为您还应该提供参数[: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
于 2010-11-02T07:41:08.390 回答
1

显然这是预期的行为。

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

至少我现在知道...

谢谢。

于 2009-11-18T06:38:50.127 回答
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
于 2009-11-30T23:11:38.093 回答
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

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

于 2013-10-31T09:45:40.473 回答