這段代碼來自於使用rails書的敏捷web開發..我不明白代碼的這部分內容... 用戶是一個名稱爲hashed_password,鹽爲字段的模型。但是在代碼中他們提到了密碼和密碼確認,而模型中沒有這樣的字段。模型只有hashed_password。我相信錯誤與我同在。請爲我清除:) 用戶模型有名稱,hashed_password,salt。所有字段都是字符串使用rails的敏捷web開發
require 'digest/sha1'
class User < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
attr_accessor :password_confirmation
validates_confirmation_of :password
validate :password_non_blank
def self.authenticate(name, password)
user = self.find_by_name(name)
if user
expected_password = encrypted_password(password, user.salt)
if user.hashed_password != expected_password
user = nil
end
end
user
end
def password
@password
end
def password=(pwd)
@password = pwd
return if pwd.blank?
create_new_salt
self.hashed_password = User.encrypted_password(self.password, self.salt)
end
private
def password_non_blank
errors.add(:password,"Missing password")if hashed_password.blank?
end
def create_new_salt
self.salt = self.object_id.to_s + rand.to_s
end
def self.encrypted_password(password, salt)
string_to_hash = password + "wibble" + salt
Digest::SHA1.hexdigest(string_to_hash)
end
end
謝謝...這部分代碼 attr_accessor:password_confirmation validates_confirmation_of:password – felix 2010-05-04 18:13:50