【问题标题】:Generate reset password token don't save on model生成重置密码令牌不保存在模型上
【发布时间】:2012-10-28 19:40:09
【问题描述】:

您好,我正在尝试为我的 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。

有人可以帮帮我吗?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3.2 railscasts


    【解决方案1】:

    当您在模型实例上调用 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 验证器。

    推荐阅读:

    【讨论】:

    • 非常感谢。我会接受你的回答,但是stackoverflow说我要等5分钟。
    猜你喜欢
    • 2012-09-16
    • 1970-01-01
    • 2015-09-23
    • 2017-02-03
    • 2018-09-30
    • 2013-11-29
    • 2018-06-15
    • 2014-06-20
    相关资源
    最近更新 更多