Sanket Meghani
Sanket Meghani

Reputation: 905

Rails - undefined method `authenticate'

I am receiving following error while trying to authenticate a user.

NoMethodError (undefined methodauthenticate' for #)`

user.authenticate('password') is successful(i.e returns the user object) when I execute the command from rails console.

irb(main):008:0> user.authenticate("sanket")
=> #<User id: 2, name: "Sanket", email: "[email protected]", created_at: "2014-02-14 08:58:28", updated_at: "2014-02-14 08:58:28", password_digest: "$2a$10$KNuBgvqVDIErf3a24lMcaeNt1Hyg0I8oreIQSEYsXY4T...", remember_token: "3b64273a4fcced7c8bf91f7f7490e60a5919658d">

However when I put user.authenticate in a helper class, and access it using a url, it says

undefined method 'authenticate' for #<ActiveRecord::Relation:0x007fd9506dce38>

I am following Rails Tutorial

My user model looks like:

class User < ActiveRecord::Base        
    attr_accessible :email, :name, :password, :password_confirmation
    has_secure_password

    .
    .
    .
end

Related method in session_helper.rb looks like:

def create
    user = User.where(:email => params[:session][:email].downcase)

    if user && user.authenticate(params[:session][:password])
        sign_in user
        redirect_to user
    else
        flash.now[:error] = 'Invalid email/password combination'
        render "new"
    end
end

It gives above error on if user && user.authenticate(params[:session][:password]) line.

What surprises me is, it is working from rails console, however the same call is not working from rails server.

Upvotes: 3

Views: 7526

Answers (1)

Mik
Mik

Reputation: 4187

As you can see in your error, where returns a relation, not a single object.

Check the related question: Why does a single record lookup return an array? (Rails beginner)

In your case, you can add first to the end of method chain, so it will return the first element of this relation:

user = User.where(:email => params[:session][:email].downcase).first

Upvotes: 11

Related Questions