【问题标题】:Requiring User to Enter Password in order to Update Profile要求用户输入密码以更新配置文件
【发布时间】:2011-04-28 18:15:00
【问题描述】:

在我的更新用户个人资料表单中,第一个字段要求用户输入她当前的密码。当她提交表单时,我会先验证密码,然后再接受其他字段的更改。以下是我目前在用户控制器中执行此操作的方式:

def update
  @user = User.find(params[:id])
  if @user.has_password?(params[:user][:password])
    if @user.update_attributes(params[:user])
      flash[:success] = "Profile updated."
      redirect_to @user
    else
      render 'edit'
    end
  else
    flash[:failure] = "Password does not match!"
    render 'edit'
  end
end

我觉得有更好的方法来做到这一点。例如,我可以使密码匹配用户模型中的验证。然后,formtastic 会自动为我处理错误消息(与上面我丑陋的 flash 方法相反)。我试过这样做

validate :password_match?, :on => :update

还有

def password_match?
  has_password(params[:user][:password])
end

但由于模型无法访问可疑参数。

我在 SO 中搜索了 20 分钟以寻找一种方法来执行此操作,但找不到任何不涉及 Devise 或 Authlogic 的内容。我正在从头开始进行身份验证(一切正常:登录、会话等)。

请让我看到更好的道路!

【问题讨论】:

  • 如果您使用过devise,这将在edit user registration view 中为您内置
  • 下次我肯定会使用设计。我最近学习了 Rails,并遵循了一个涉及从头开始构建身份验证的教程。从那以后,我一直在为我的项目编写代码。

标签: ruby-on-rails


【解决方案1】:

您不需要设计,只需在更新时在控制器上使用前置过滤器 在您的个人资料控制器上。

before_filter password_match, :only => :update

然后在底部作为私有。


private

def password_match
   @user = User.find(params[:id])
   @user.has_password?(params[:user][:password])

【讨论】:

  • 这条路让我掉进了兔子洞。将您拖入上下文可能不值得,我们必须来回多次。我只会坚持我原来的解决方案。我认为这可能归结为我不知道如何使用 errors.add 正确地将自定义错误添加到密码字段。无论如何,接受答案,因为这是一个很好的建议。
  • 去喝杯咖啡休息片刻。你不需要errors.add,屏幕顶部的一个漂亮的flash错误怎么样?只需添加一个 flash.now[:error] = 'The password doesn't match your current password' 就是这样:)
  • 这实际上是我最初的方法,请参见上面的第一个代码示例。我决定坚持下去。
猜你喜欢
  • 1970-01-01
  • 2013-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-22
相关资源
最近更新 更多