您好,我正在尝试为我的 Rails 应用程序创建一个重置密码;但是当我尝试保存时出现以下错误:
Validation failed: Password can't be blank, Password is too short (minimum is 6 characters), Password confirmation can't be blank
这是我的用户模型。
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。
请问有人能帮帮我吗?
最佳答案
当您在模型实例上调用 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
验证器。
推荐阅读:
关于ruby-on-rails - 生成重置密码 token 不保存在模型上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13112308/