1
这一直在踢我的屁股整个早晨。Michael Hartl的Rails 3教程:has_password问题?方法在第7章
现在,我刚刚开始迈克尔·哈特的优秀的第7.2.4章第3章教程,我遇到了一些问题。本节首先在Rails控制台沙箱中快速检查has_password?
方法。下面是我在已经输入:
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: "[email protected]", created_
at: nil, updated_at: nil, encrypted_password: nil, salt: nil>
ruby-1.9.2-p180 :003 > user = User.find_by_email("[email protected]"
ruby-1.9.2-p180 :004?> )
=> #<User id: 1, name: "John Pavlick", email: "[email protected]", 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+\-.][email protected][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
测试全部通过完美的,而据我所知,我在书逐字一切已经编码 - 我甚至复制/粘贴一些代码来确保。我认为没有任何理由可以解决这个问题,所以任何帮助都将是一个救星。
这里的书的链接,在线:[link]
非常感谢!结果我早些时候用数据库中的信息创建了一条记录 - 当我在':name'和':email:'中使用不同的信息时,它完美的工作!再次感谢! – eckza 2011-04-18 17:32:21
添加到DGM所说的内容中,您应该能够运行'rake db:reset',然后尝试创建记录。 (我认为。) – Tass 2011-04-18 17:35:10