这整个早上都在踢我的屁股。
现在,我刚刚开始 Michael Hartl 的优秀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")
=> #<User id: nil, name: "John Pavlick", email: "jmpavlick@gmail.com", created_
at: nil, updated_at: nil, encrypted_password: nil, salt: nil>
ruby-1.9.2-p180 :003 > user = User.find_by_email("jmpavlick@gmail.com"
ruby-1.9.2-p180 :004?> )
=> #<User id: 1, name: "John Pavlick", email: "jmpavlick@gmail.com", created_at
: "2011-04-15 15:11:46", updated_at: "2011-04-15 15:11:46", encrypted_password:
nil, salt: nil>
ruby-1.9.2-p180 :005 > user.has_password?("foobar")
=> false
这应该是返回true
。
这是我的user.rb
模型:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
email_regex = /^[\w+\-.]+@[a-z\d\-.]+\.[a-z]+$/i
validates :name, :presence => 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
测试都完美通过了,据我所知,我已经逐字编码了书中的所有内容——我什至复制/粘贴了一些代码以确保。我根本看不出有任何失败的理由,所以任何帮助都将成为救命稻草。
这是本书的在线链接:[链接]