我正在读一本书(Beginning Rails 3),但在Rails 4上尝试了一切。
所以,我有一个问题:
def self.authenticate(email, password)
user = where('email = ?', email)
return user if user && user.authenticated?(password)
end
def authenticated?(password)
self.hashed_password == encrypt(password)
end
当我在rails console
中执行此操作时:
User.authenticate('test@test.com', 123)
Rails返回错误Undefined method authenticated?
。
irb(main):034:0> User.authenticate('test@test.com', 123)
NoMethodError: ←[1m←[35mUser Load (1.0ms)←[0m SELECT "users".* FROM "users" WHERE (email = 'test@test.com')
undefined method `authenticated?' for #<ActiveRecord::Relation []>
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/relation/delegati
on.rb:121:in `method_missing'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activerecord-4.0.0/lib/active_record/relation/delegati
on.rb:68:in `method_missing'
from C:/Sites/rails-estudo-blog/app/models/user.rb:23:in `authenticate'
from (irb):34
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `st
art'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `sta
rt'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (requ
ired)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
irb(main):035:0>
怎么了?
答案 0 :(得分:1)
而不是user = where('email = ?', email)
您应该user = where('email = ?', email).first