Patrick Maciel
Patrick Maciel

Reputation: 4944

Undefined authenticated? method in Rails 4

I'm reading a book (Beginning Rails 3), but trying everything on Rails 4.

So, I have one problem:

  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

When I do that in rails console:

User.authenticate('[email protected]', 123)

Rails returns me an error, Undefined method authenticated?.

  irb(main):034:0> User.authenticate('[email protected]', 123)
  NoMethodError:   ←[1m←[35mUser Load (1.0ms)←[0m  SELECT "users".* FROM "users" WHERE (email = '[email protected]')
  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>

What's wrong?


Upvotes: 0

Views: 980

Answers (1)

Iuri G.
Iuri G.

Reputation: 10630

instead of user = where('email = ?', email) you should have user = where('email = ?', email).first

Upvotes: 1

Related Questions