我对Ruby完全陌生,并试图学习该语言。我正在使用Agile Web Development with Rails一书,在关于创建使用帐户的章节中,我一直收到错误:
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ykj1a4971bgeEXuftslIgPErK67VTvPlTpcg//Wx8R8=", "user"=>{"name"=>"testaccount", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create User"}
Completed 500 Internal Server Error in 16ms
NoMethodError (undefined method `salt=' for #<User:0x00000009008b70>):
app/models/user.rb:41:in `generate_salt'
app/models/user.rb:29:in `password='
app/controllers/users_controller.rb:43:in `new'
app/controllers/users_controller.rb:43:in `create'
以下是我的user.rb文件中的代码:
require 'digest/sha2'
class User < ActiveRecord::Base
validates :name, :presence => true, :uniqueness => true
validates :password, :confirmation => true
attr_accessor :password_confirmation
attr_reader :password
validate :password_must_be_present
def User.authenticate(name, password)
if user = find_by_name(name)
if user.hashed_password == encrypt_password(password, user.salt)
user
end
end
end
def User.encrypt_password(password, salt)
Digest::SHA2.hexdigest(password + "wibble" + salt)
end
# 'password' is a virtual attribute
def password=(password)
@password = password
if password.present?
generate_salt
self.hashed_password = self.class.encrypt_password(password, salt)
end
end
private
def password_must_be_present
errors.add(:password, "Missing password") unless hashed_password.present?
end
def generate_salt
self.salt = self.object_id.to_s + rand.to_s
end
end
任何想法可能导致我的问题。如果您需要更多信息,请告诉我列出代码的文件。
答案 0 :(得分:3)
答案 1 :(得分:-1)
这是因为salt
未在该模型中定义。
你已经有了这个:
attr_accessor :password_confirmation
您可以做的是在该行下方添加:
attr_accessor :salt
这应该有用。