【问题标题】:Is there a better way to validate in Rails?有没有更好的方法在 Rails 中进行验证?
【发布时间】: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 那太完美了!正是我需要的。你能把它作为答案让我接受吗?

标签: ruby-on-rails validation


【解决方案1】:

Conditional Validations

打算建议你使用某种conditional validations,如下(然后我阅读了cmets):

#app/models/consumer.rb
class Consumer < ActiveRecord::Base
      ...
      validates :password_confirmation, presence: {message: "Retype password!"}, if: Proc.new {|a| a.password.present? }
end

这是我能为您的特殊情况提供的最好的方法 - 我自己没有创建 password 注册/身份验证程序(总是依赖于其他类),所以如果您想使用 has_secure_password 等 - 我'我必须更新我的答案以提供帮助

【讨论】:

  • password_confirmation 部分本身不是问题。问题是 password 和 password_confirmation 都只在“创建”和“更新密码”两种情况下使用,更新模型中的其他值可能并不意味着更新密码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 2013-09-17
  • 2019-09-01
  • 2020-12-11
  • 2013-12-09
  • 1970-01-01
相关资源
最近更新 更多