Kane
Kane

Reputation: 924

Cannot call .authenticate method in has_secure_password

Sessions controller:

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by_email(params[:email])
    if user && User.authenticate(params[:password])
        session[:user_id] = user.id
        redirect_to products_path, notice: 'Logged in successfully'
    else
        flash.now.alert = "Email or password is invalid"
        render 'new'
    end
  end

  def destroy
  end
end

User model:

class User < ActiveRecord::Base
  has_secure_password

  attr_accessible :email, :password, :password_confirmation

  validates_uniqueness_of :email
end

Log in form:

<h1>Login form</h1>

<%= form_tag sessions_path do %>

    <%= label_tag :email %><br/>
    <%= text_field_tag :email, params[:email] %><br/>

    <%= label_tag :password %><br/>
    <%= password_field_tag :password, params[:password] %><br/>

    <%= submit_tag "Login" %>
<% end %>

When I try to use my login form a NoMethodError is raised stating that authenticate is undefined.

I thought that the authenticate method was provided by putting has_secure_password in the user model? Am I wrong here?

Any help appreciated!

Upvotes: 2

Views: 1461

Answers (1)

Naveen Kumar
Naveen Kumar

Reputation: 200

I believe you need to authenticate on user object, Try with this

def create
    user = User.find_by_email(params[:email])
    if user && user.authenticate(params[:password])
        session[:user_id] = user.id
        redirect_to products_path, notice: 'Logged in successfully'
    else
        flash.now.alert = "Email or password is invalid"
        render 'new'
    end
  end

Upvotes: 3

Related Questions