2012-03-03 96 views
0

我有以下的模型,我試圖用這個Rails Validates Prevents Save確定password_required的正確位置?用before_save密碼加密

class User < ActiveRecord::Base 
    before_save :encrypt_password 
    validates :password, :presence => true, 
        :confirmation => true, 
        :length => { :within => 4..12 }, 
        :if => :password_required? 

    def password_required?   
    self.new_record? or self.password? 
    end 

    # 
    # where we encrypt on creation 
    # 
    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 

我得到一個錯誤關閉密碼驗證的用戶模式:

undefined method `password?' for #<User:0x007fc8e0473be0> 

我應該檢查self.password_hash?還有另一種更新密碼的形式。在這種情況下關閉驗證的最佳策略是什麼?

THX

回答

1

你應該添加到您的用戶模型:

attr_accessor :password 

這將會給你的用戶模型中的密碼屬性 - 然而,它不保存到數據庫或應用程序記以任何方式。只有鹽和散列被存儲。

獲取密碼?在模型中也做到這一點:

attr_accessor :password 
alias :password? :password 

您可以使用password?像gimpy布爾字段:如果返回任何東西,然後設置密碼。否則,密碼尚未設置。

+0

thx,這是有道理的,但仍然收到錯誤「未定義的方法'密碼?爲#<用戶:0x007fc8e05da5b0>'。 Noob在鐵軌上。 self.password的語法是什麼?離 – timpone 2012-03-04 13:18:35