Reputation:
In my ApplicationController, there is current_use
.
private
def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end
def logged_in?
!!session[:user_id]
end
logged_in?
and authenticate works. However, when I change
<% if logged_in? %>
to
<% if logged_in? && current_user.free? %>
in views/top/index.html.erb, following error occurs.
NameError at /
undefined local variable or method `current_user' for #<#<Class:...>:...>
How do I solve this?
free?
is defined in user.rb as
def free?
visit.game.count == 0
end
Added
If I change current_user
to @current_user
, error message become as follows.
NoMethodError at /
undefined method `free?' for nil:NilClass
Upvotes: 5
Views: 12095
Reputation: 28800
I had this issue when working on a Rails 6 API only application with the Pundit gem and the JWT gem for authentication.
I was running into this error when trying to test a Pundit authorization for a controller action:
NameError: undefined local variable or method `current_user' for #Api::V1::SchoolsController:0x00007f30a4918120\nDid you mean? @current_user
Here's how I fixed:
The current_user
method seemed unavailable to Pundit so it was throwing that error when it could not find it.
I simply defined a pundit_user
in the app/controllers/application_controller.rb
file:
class ApplicationController < ActionController::API
include Pundit
def pundit_user
header = request.headers['Authorization']
header = header.split(' ').last if header
@decoded = JsonWebToken.decode(header)
User.find(@decoded[:user_id])
rescue ActiveRecord::RecordNotFound => e
render json: { errors: e.message }, status: :unauthorized
rescue JWT::DecodeError => e
render json: { errors: e.message }, status: :unauthorized
end
end
That's all.
I hope this helps
Upvotes: 1
Reputation: 6398
Just try and add this to your application controller:
helper_method :current_user
What this does is that it makes the private method as a helper method and it is accessible in all the controllers and views. Hope this helps.
Upvotes: 7