Sachin
Sachin

Reputation: 277

NoMethodError (undefined method `errors' for nil:NilClass):

We are getting the above mentioned error, not quite sure why. We are building API for a quiz website, and this is our logins_controller:

 class Api::LoginsController < ApplicationController

    skip_before_action :verify_authentication

    def create
        user = User.find_by_username(params[:username])
        if  user && user.authenticate(params[:password])
            render json: { name: user.name, token: user.token }
        else
            render json: user.errors
        end
    end
 end

Our schema:

create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "username"
    t.string "password_digest"
    t.string "token"
    t.boolean "admin"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["token"], name: "index_users_on_token", unique: true
  end

Error message in terminal:

Started POST "/api/logins" for 127.0.0.1 at 2018-09-23 18:30:48 -0400
Processing by Api::LoginsController#create as */*
  Parameters: {"login"=>{}}
  User Load (4.2ms)  SELECT  "users".* FROM "users" WHERE "users"."username" IS NULL LIMIT $1  [["LIMIT", 1]]
  ↳ app/controllers/api/logins_controller.rb:6
Completed 500 Internal Server Error in 8ms (ActiveRecord: 4.2ms)



NoMethodError (undefined method `errors' for nil:NilClass):

app/controllers/api/logins_controller.rb:10:in `create'

This was working just fine, then all of a sudden it says user is nil? Have we not defined it under create.

Upvotes: 0

Views: 2112

Answers (4)

Sachin
Sachin

Reputation: 277

Looked through some codes, didn't alter much, but simply changing user to @user everywhere seemed to get it working!

Upvotes: 0

H Dox
H Dox

Reputation: 675

If a user with username is not exists in your database, the following code will return nil

user = User.find_by_username(params[:username])

As a result, you will get undefined method errors when calling user.errors

Upvotes: 0

Siri Bunnamon
Siri Bunnamon

Reputation: 116

You didn't send any parameters to the controller

In your terminal: Parameters: {"login"=>{}}

user = User.find_by_username(params[:username]) 

so the user variable will be nil

Upvotes: 0

Rodrigo
Rodrigo

Reputation: 4802

When the parameter :username doesn't match any user, the user variable will be nil.

Upvotes: 1

Related Questions