使用 Rails 3.1.3。我正在使用 railscast 270 中提供的密码验证方法来调用“has_secure_password”:
class User < ActiveRecord::Base
has_secure_password
end
除了一个非常令人费解的问题外,它有效。文档说明使用
user.authenticate("不正确")
但是我看不到在哪里声明了 authenticate 方法。我查看了secure_password,一个看似等效的方法是:
# Returns self if the password is correct, otherwise false.
def get_logged_in_user(unencrypted_password)
if BCrypt::Password.new(password_digest) == unencrypted_password
self
else
false
end
end
请注意,我正在尝试从 railstutorial.org 转换示例(真的很棒),所以我必须更改很多内容,并且我的应用程序中可能存在冲突的内容。例如,我以前有这行:
attr_accessor :password
这阻止了在 secure_password 中调用 password= 的声明,导致 password_digest 的 db 列为零。删除此行解决了此问题。
更新:我用 3.1.3 创建了一个全新的 rails 应用程序,并确认运行这两个命令的最简单情况会导致错误:
u = User.create(:username => "a", :password => "foobar", :password_confirmation => "foobar") (0.1ms) BEGIN SQL (0.2ms) INSERT INTO
users
(created_at
,password_digest
,updated_at
,username
) VALUES (' 2011-12-21 05:18:17', '$2a$10$BbwHbq1bGwvQRgE0xK28VeP8K/lwY.VfLaLsMSs6ogNa1DucephnK', '2011-12-21 05:18:17', 'a') (42.6ms) 提交u.authenticate("foobar") u.authenticate("foobar") NoMethodError: undefined method
authenticate' for #<User:0xa26e4cc> from /home/justin/.rvm/gems/ruby-1.9.3-p0@testapp/gems/activemodel-3.1.3/lib/active_model/attribute_methods.rb:385:in
method_missing' from /home/justin/.rvm/gems/ruby-1.9.3-p0@testapp/gems/activerecord-3.1.3 /lib/active_record/attribute_methods.rb:60:inmethod_missing' from (irb):4 from /home/justin/.rvm/gems/ruby-1.9.3-p0@testapp/gems/railties-3.1.3/lib/rails/commands/console.rb:45:in
start' from /home/justin/.rvm/gems/ruby-1.9.3-p0@testapp/gems/railties-3.1.3/lib/rails/commands/console .rb:8:instart' from /home/justin/.rvm/gems/ruby-1.9.3-p0@testapp/gems/railties-3.1.3/lib/rails/commands.rb:40:in
' 来自 /home/justin/j/RubymineProjects/auth/script/rails:6:inrequire' from /home/justin/j/RubymineProjects/auth/script/rails:6:in
' 来自 -e:1:inload' from -e:1:in
'
更新:这绝对是 ruby 1.9.3 的某种问题。我在 1.9.2 上尝试了相同的 gem,我没有任何问题。