有没有更好的方法在Rails中验证?

时间:2014-06-20 05:28:03

标签: ruby-on-rails validation

在我的模型中,我有验证是否存在“password”和“password_confirmation”字段。在创建模型时,验证运行正常。但在更新模型期间,即使在更新一组特定字段时,似乎也会在整个模型上调用验证。由于我每次都没有传递“password”和“password_confirmation”字段,因此验证失败。

起初我的想法是仅仅在“on: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

1 个答案:

答案 0 :(得分:0)

Conditional Validations

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

#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等 - 我将不得不更新我的答案