簡體   English   中英

有沒有更好的方法在Rails中進行驗證?

[英]Is there a better way to validate in Rails?

在我的模型中,我具有驗證來檢查“ password”和“ password_confirmation”字段是否存在。 在創建模型時,驗證運行良好。 但是在更新模型期間,即使在更新一組特定字段時,似乎也需要對整個模型進行驗證。 而且由於我每次都沒有傳遞“ password”和“ password_confirmation”字段,因此驗證失敗。

最初,我的想法是僅在“: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

條件驗證

將建議您使用某種條件驗證 ,如下所示(然后我閱讀了注釋):

#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等-我必須將答案更新為救命

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM