2012-10-28 99 views
2

你好,我試圖爲我的Rails應用程序創建一個重置密碼;但是當我嘗試保存時出現以下錯誤:生成重置密碼令牌不保存在模型上

Validation failed: Password can't be blank, Password is too short (minimum is 6 characters), Password confirmation can't be blank

這是我的用戶模型。

class User < ActiveRecord::Base 
    attr_accessible :email, :password, :password_confirmation 
    has_secure_password 

    before_save { |user| user.email = email.downcase } 
    before_save :create_remember_token 

    VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 
    validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } 
    validates :password, presence: true, length: { minimum: 6 } 
    validates :password_confirmation, presence: true 

    def send_password_reset 
     self.password_reset_token = SecureRandom.urlsafe_base64 
     self.password_reset_at = Time.zone.now 
     self.password = self.password 
     self.password_confirmation = self.password 
     save! 
    end 

    private 

    def create_remember_token 
     self.remember_token = SecureRandom.urlsafe_base64 
    end 

end 

方法「send_password_reset」不更新的用戶,我不明白爲什麼試圖保存用戶上,而不是隻更新password_reset_token和password_reset_at。

有人可以幫助我嗎?

回答

8

當您在模型實例上調用save!時,它將在您的User模型上運行驗證;他們全部。

有許多方法可以有條件地跳過密碼驗證。一種方法是使用一個Proc

validates :password, presence: true, length: { minimum: 6 }, unless: Proc.new { |a| !a.new_record? && a.password.blank? } 

這將允許要保存的User實例,將跳過:password領域的驗證,如果是空白,User是不是新(已保存到數據庫)

這是最讓我用一個密碼驗證的在我的應用程序

validates :password, confirmation: true, 
        length: {:within => 6..40}, 
        format: {:with => /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){6,40}$/}, 

注意,你不需要在:password_confirmation獨立驗證。而只需將confirmation: true傳遞給:password驗證程序。

推薦閱讀:

+0

非常感謝你。我會接受你的回答,但是stackoverflow說我必須等5分鐘。 – Jean