【发布时间】:2023-04-05 10:35:01
【问题描述】:
在我的模型中,我有检查“密码”和“密码确认”字段是否存在的验证。在创建模型时,验证运行良好。但是在更新模型期间,即使在更新一组特定字段时,似乎也会对整个模型调用验证。而且由于我没有每次都传入“密码”和“密码确认”字段,因此验证失败。
起初我的想法是仅在“:create”上验证这两个字段,但我也想提供更新密码的选项。在这种情况下,这些字段的更新期间不会调用验证。
那么,有没有办法解决这个问题?
以下是我的模型:
class Consumer < ActiveRecord::Base
attr_accessor :password, :password_confirmation
mount_uploader :image, ProfileImageUploader
EMAIL_REGEX = /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
PASS_REGEX = /\A[a-zA-Z0-9]{8,16}\z/
validates :email, presence: {message: "Email cannot be blank!", on: :create}, format: {with: EMAIL_REGEX, message: "Email invalid!"}
validate :unique_email?, on: :create
validates :password, presence: {message: "Password cannot be blank!"}, confirmation: {message: "Passwords do not match!"}, format: {with: PASS_REGEX, message: "Password invalid!"}
validates :password_confirmation, presence: {message: "Retype password!"}
validates :fullname, presence: {message: "Name cannot be empty!"}
before_save :encrypt_password
def authenticate pass
new_hash = BCrypt::Engine.hash_secret pass, self.password_salt
if new_hash === self.password_hash
return true
end
false
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret password, password_salt
end
end
end
【问题讨论】:
-
我认为当您已经在使用 bcrypt-ruby 时,您不需要对 password_confirmation 进行验证,因为它默认检查 password_confirmation,此外,您已经在密码验证中使用了 password_confirmation。我想就是这样,你可以用
has_secure_password代替我猜? -
哈哈我不敢相信我遇到了这个问题,我今天早些时候只是想知道同样的事情。看看这个 railscast:railscasts.com/episodes/41-conditional-validations 这几乎就是我所做的,除了适应我的项目。
-
@Xerif917 那太完美了!正是我需要的。你能把它作为答案让我接受吗?