Rails 如果用户记录包含无效数据,设计重置密码失败

Rails devise reset password fails if user record contains invalid data

我在生产中有一个现有应用程序,我们在其中向用户记录添加了新的必填字段。结果,忘记密码功能失效。我相信失败发生在 recoverable.rb

中的以下方法中
  # Update password saving the record and clearing token. Returns true if
  # the passwords are valid and the record was saved, false otherwise.
  def reset_password(new_password, new_password_confirmation)
    if new_password.present?
      self.password = new_password
      self.password_confirmation = new_password_confirmation
      save
    else
      errors.add(:password, :blank)
      false
    end
  end

无法机械生成新属性。只有用户自己会知道正确的值。有谁知道解决这个问题的方法吗?

目前我唯一的想法如下:

您可以使用 自定义验证上下文 来确保这些添加字段的验证仅在用户编辑其个人资料时 运行,但在(对于example) Devise 保存用户记录。

在用户模型中,为这些验证添加一个 on: 子句

validates_presence_of :recently_added_mandatory_field, on: :user_updates_profile

并在适当的控制器操作中,在调用 #valid?#save 时添加此验证上下文:

# Existing code uses `@user.valid?` -> change to:
if @user.valid?(:user_updates_profile)
  …

# Existing code uses `@user.save` -> change to:
if @user.save(context: :user_updates_profile)
  …

有关验证上下文的完整说明,请参阅此处:https://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates