0
我有與在this question中描述的完全相同的問題,但出於不同的原因,顯然。has_password問題?方法在railstutorial.org(第7章)
This是本書的相關部分。
我已經完全按照書上所做的,據我所知,我的rspec測試都工作正常。
我的用戶模型代碼是這樣的:
require 'digest' #Needs digest to do password encryption
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
validates :name, :presence => true,
:length => { :maximum => 20 }
email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :password, :presence => true,
:confirmation =>true,
:length => { :within => 5..24 }
before_save :encrypt_password
def has_password?(submitted_password)
encrypt_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
正如我所說的,測試都工作正常,但has_password?總是在控制檯中返回false。 這是我在控制檯那樣:
ruby-1.9.2-p180 :002 > User.create!(:name => 'userdude', :email => '[email protected]', :password => 'foobar', :password_confirmation => 'foobar')
=> #<User id: 2, name: "userdude", email: "[email protected]", created_at: "2011-07-28 23:13:40", updated_at: "2011-07-28 23:13:40", encrypted_password: "84f9a1348af1f7e6610fb1d0c7002efe96f43dc97d807b3ac00...", salt: "13cf7bfd386af4fcf282ae5fa4831eb9d1dff15e842be8cba88...">
ruby-1.9.2-p180 :003 > User.all
=> [#<User id: 2, name: "userdude", email: "[email protected]", created_at: "2011-07-28 23:13:40", updated_at: "2011-07-28 23:13:40", encrypted_password: "84f9a1348af1f7e6610fb1d0c7002efe96f43dc97d807b3ac00...", salt: "13cf7bfd386af4fcf282ae5fa4831eb9d1dff15e842be8cba88...">]
ruby-1.9.2-p180 :004 > user = User.first
=> #<User id: 2, name: "userdude", email: "[email protected]", created_at: "2011-07-28 23:13:40", updated_at: "2011-07-28 23:13:40", encrypted_password: "84f9a1348af1f7e6610fb1d0c7002efe96f43dc97d807b3ac00...", salt: "13cf7bfd386af4fcf282ae5fa4831eb9d1dff15e842be8cba88...">
ruby-1.9.2-p180 :005 > user
=> #<User id: 2, name: "userdude", email: "[email protected]", created_at: "2011-07-28 23:13:40", updated_at: "2011-07-28 23:13:40", encrypted_password: "84f9a1348af1f7e6610fb1d0c7002efe96f43dc97d807b3ac00...", salt: "13cf7bfd386af4fcf282ae5fa4831eb9d1dff15e842be8cba88...">
ruby-1.9.2-p180 :006 > user.has_password?('foobar')
=> false
ruby-1.9.2-p180 :007 >
正如你看到的,有沒有創建任何記錄,因爲在我掛了另一個問題。
是的!謝謝!我瘋了。現在我更仔細地閱讀它,我看到它:我拼錯了encrypted_password,它可能是編輯器自動完成。 –
當然,這些測試是成功的......我從來沒有發現錯誤 –