Michael Hartl的Rails 3教程:has_password问题? 第7章中的方法

整个上午都在踢我的屁股。

现在,我刚刚开始迈克尔哈特尔出色的Ruby on Rails 3教程的第7.2.4章,我遇到了一些问题。 该部分首先快速检查has_password? 方法,在Rails控制台沙箱中。 这是我输入的内容:

 ruby-1.9.2-p180 :001 > User => User(id: integer, name: string, email: string, created_at: datetime, updated updated_at: datetime, encrypted_password: string, salt: string) ruby-1.9.2-p180 :002 > User.create(:name => "John Pavlick", :email => "jmpavlick @gmail.com", :password => "foobar", :password_confirmation => "foobar") => # ruby-1.9.2-p180 :003 > user = User.find_by_email("jmpavlick@gmail.com" ruby-1.9.2-p180 :004?> ) => # ruby-1.9.2-p180 :005 > user.has_password?("foobar") => false 

这应该是true

这是我的user.rb模型:

 class User  true, :length => { :maximum => 50 } validates :email, :presence => true, :format => { :with => email_regex }, :uniqueness => { :case_sensitive => false } # Automatically create the virtual attribute 'password confirmation' validates :password, :presence => true, :confirmation => true, :length => { :within => 6..40 } before_save :encrypt_password # Return true if the user's password matches the submitted password def has_password?(submitted_password) encrypted_password == encrypt(submitted_password) end private def encrypt_password self.salt = make_salt if new_record? self.encrypted_password = encrypt(password) end def encrypt(string) secure_hash("#{salt}--#{string}") end def make_salt secure_hash("#{Time.now.utc}--#{password}") end def secure_hash(string) Digest::SHA2.hexdigest(string) end end 

我所有的RSpec测试都完美无缺,据我所知,我已逐字编码书中的所有内容 – 我甚至复制/粘贴了一些代码以确保。 我认为没有任何理由可以失败,所以任何帮助都将成为救星。

这是这本书的链接,在线: [链接]

在创建调用之后,请注意返回的对象没有id或加密密码…我怀疑validation失败并且没有创建记录,可能是因为您已经有记录存在?