I have a user controller I am using Rails 6 API and I am using the JWTSessions gem to authenticate users in the documentation it tells me to add the following method:
class ApplicationController < ActionController::API
include JWTSessions::RailsAuthorization
rescue_from ActionController::ParameterMissing, with: :bad_request
rescue_from ActiveRecord::RecordInvalid, with: :unprocessable_entity
rescue_from ActiveRecord::RecordNotFound, with: :not_found
rescue_from JWTSessions::Errors::Unauthorized, with: :not_authorized
rescue_from JWTSessions::Errors::ClaimsVerification, with: :forbidden
rescue_from ResetPasswordError, with: :not_authorized
private
def current_user
@current_user ||= User.find(payload['user_id'])
end
end
By calling the current_user method from users_controller.rb
class UsersController < ApplicationController
before_action :authorize_access_request!
def me
render json: current_user
end
end
The route to call the me method is the following routes.rb
Rails.application.routes.draw do
post 'refresh', controller: :refresh, action: :create
post 'signin', controller: :signin, action: :create
post 'signup', controller: :signup, action: :create
delete 'signin', controller: :signin, action: :destroy
get 'me', controller: :users, action: :me
end
I have correctly logged in the user but when calling the method I get the following error
undefined local variable or method `current_user'
Could you help me because it marks the error if I am adding the corresponding methods, thanks
You have your
current_user
asprivate
, so you can only call it fromApplicationController
. If you want to call it from controllers that inherit fromApplicationController
, you must declare the method asprotected
or leave it public.