1

我希望用户成功确认他们当前的密码以更改他们的密码。我最初在控制器#update 上有一些东西,但似乎向虚拟属性添加错误不会使实例无效,因为没有阻止保存。

我正在使用 has_secure_password。我现在已经切换到模型中的验证,但是下面的代码总是无法验证,因为身份验证返回 false。我在控制台中做了一些测试,发现如果我这样做了

user = User.first
user.current_password = 'thecurrentpassword'
user.password = 'thenewpassword'
user.valid?  => false
user.authenticate('thecurrentpassword') => false
user.authenticate('thenewpassword') => true ... before saving

所以似乎 password_digest 在分配新密码而不是保存时被重置?如果他们的 current_password 在模型层或控制器层错误,我该如何解决这个问题并简单地阻止记录保存?

validate  :validate_current_password, if: Proc.new{ |u| u.persisted? and u.password.present? }

  def validate_current_password
    unless authenticate(current_password)
      errors.add(:current_password, 'invalid password')
    end
  end
4

1 回答 1

2

您可以添加一个类方法,如下所示:

class User
  def self.authenticate(email, password)
    find_by_email(email).try(:authenticate, password)
  end
end

现在任何控制器都可以查明给定的电子邮件 + 密码组合是否是有效用户。

于 2012-04-07T13:13:02.253 回答