2012-03-03 97 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