0

我正在读一本书(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>

怎么了?


  • 导轨 4.0
  • 红宝石 2.0
  • 视窗 7 x64
4

1 回答 1

1

而不是user = where('email = ?', email)你应该有user = where('email = ?', email).first

于 2013-09-24T15:44:51.510 回答