2

您好,我正在尝试为我的 rails 应用程序创建重置密码;但是当我尝试保存时,出现以下错误:

验证失败:密码不能为空、密码太短(最少为 6 个字符)、密码确认不能为空

这是我的用户模型。

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation
  has_secure_password

  before_save { |user| user.email = email.downcase }
  before_save :create_remember_token

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
  validates :password, presence: true, length: { minimum: 6 }
  validates :password_confirmation, presence: true

    def send_password_reset
        self.password_reset_token = SecureRandom.urlsafe_base64
        self.password_reset_at = Time.zone.now
        self.password = self.password
        self.password_confirmation = self.password
        save!
    end

  private

    def create_remember_token
        self.remember_token = SecureRandom.urlsafe_base64
    end

end

方法“send_password_reset”不会更新用户,我不明白为什么要尝试保存用户而不是仅更新 password_reset_token 和 password_reset_at。

有人可以帮助我吗?

4

1 回答 1

8

当您调用save!模型实例时,它将在您的模型上运行验证User;他们全部。

有许多方法可以有条件地跳过密码验证。一种是使用Proc

validates :password, presence: true, length: { minimum: 6 }, unless: Proc.new { |a| !a.new_record? && a.password.blank? }

这将允许User保存实例,并且:password如果该字段为空且User不是新的(已持久化到数据库) ,则将跳过该字段的验证。

这是我在应用程序中使用的大部分密码验证

validates :password, confirmation: true,
                     length: {:within => 6..40},
                     format: {:with => /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){6,40}$/},

请注意,您不需要单独验证:password_confirmation. 相反,只需传递confirmation: true:password验证器。

推荐阅读:

于 2012-10-28T19:46:27.203 回答