user3048402
user3048402

Reputation: 1369

Rails 4 authenticate method undefined

I bought the book "Beginning Rails 4" on Apress and it uses user.authenticate for authentication, however it throws me an error. Afterwards I read a review saying that the book mainly covers Rails 3.2, so is this no longer supported?

I am getting the following error:

undefined method `authenticate' for #<Class:0x007f83ece1a678>

class SessionsController < ApplicationController
    def create
        if user = User.authenticate(params[:email], params[:password])
            session[:user_id] = user.id
            redirect_to root_path, :notice => "Logged in successfully"
        else

My sessions_controller.rb

class SessionsController < ApplicationController
    def create
        if user = User.authenticate(params[:email], params[:password])
            session[:user_id] = user.id
            redirect_to root_path, :notice => "Logged in successfully"
        else
            flash.now[:alert] = "Invalid login/password combination"
            render :action => 'new'
        end
    end

    def destroy
        reset_session
        redirect_to root_path, :notice => "You successfully logged out"
    end
end

View

<h1>Login</h1>

<%= form_tag session_path do %>
  <div class="field">
    <%= label_tag :email %><br />
    <%= text_field_tag :email %>
  </div>
  <div class="field">
    <%= label_tag :password %><br />
    <%= password_field_tag :password %>
  </div>
  <div class="actions">
    <%= submit_tag 'Login' %>
  </div>
<% end %>

Thanks in advance for your help.

Upvotes: 1

Views: 5311

Answers (2)

Alfredo Roca Mas
Alfredo Roca Mas

Reputation: 129

Try in the create method:

class SessionsController < ApplicationController
  def create
    user = User.where(email: params[:email]).first
    if user && user.authenticate(params[:password])

...

Notice: authenticate applies to instance variable.

Upvotes: 1

Abdo
Abdo

Reputation: 14051

You are probably missing the bcrypt-ruby gem.

Add this to your Gemfile:

gem 'bcrypt-ruby'

In your user model, you need to add:

class User < ActiveRecord::Base
  has_secure_password
  ...
end

Make sure to migrate rake db:migrate and to restart server

Upvotes: 1

Related Questions