2012-10-28 52 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