andrea2010
andrea2010

Reputation: 338

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

From the frontend sends a request for the establishment of Taska and I receive here such error:

enter image description here

There is another error on the server:

enter image description here

In the console itself, I get:

enter image description here

enter image description here

def create
  @task = current_user.tasks.new(task_params)            // It's 19 line tasks_controller

  if @task.save
    render json: @task, status: :created, location: @task
  else
    render json: @task.errors, status: :unprocessable_entity
  end
end

and

private

def task_params
  params.require(:task).permit(:title, :body)
end

current_user - application_controller.rb

def current_user
  current_user ||= User.find_by(token: request.headers['Authorization'])
end

Scheme table users.

enter image description here

I am new to all this, what is obvious to you is not known to me, therefore I am here.

Upvotes: 0

Views: 236

Answers (1)

max
max

Reputation: 102154

This is the classic do-it-yourself authentication nil error. When setting up an authentication system you should ensure that any action that requires the user to be signed in will bail early and redirect the user to the sign in or if its an API send a header that indicates that the user is not authorized.

class AuthenticationError < StandardError; end

class ApplicationController
  # locking everything down makes your app secure by default
  # use skip_before_action :authenticate_user! to allow unauthorized users 
  before_action :authenticate_user!

  rescue_from AuthenticationError, with: :handle_unauthorized_access

  private

  def authenticate_user!
    raise AuthenticationError unless current_user
  end

  def handle_unauthorized_access
    respond_to do |f|
      f.html { redirect_to '/path/to/login', notice: 'Please sign in' }
      f.json { head :unauthorized  }
    end
  end

  # ...
end

Even better is to not reinvent the wheel. Authentication is hard and we all screw it up. Thats why its good to use libraries like Devise or Knock that have tons of eyes reviewing the code.

Upvotes: 2

Related Questions