Reputation: 1666
Hi guys i've some problem with RoR. I try to define a current user like that
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def current_user
@current_user ||= User.find(session[:user_id])
end
end
that's my error : Couldn't find User without an ID
I don't know why... I've an user_id in my BBD.
Upvotes: 1
Views: 246
Reputation: 1666
The solution were
def current_user
@current_user ||= session[:user_id] && User.find(session[:user_id])
en
OR
def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end
Upvotes: 0
Reputation: 44685
you are getting this error, because there is no :user_id in your session. Try:
@current_user ||= session[:user_id] && User.find(session[:user_id])
or
@current_user ||= User.find_by(id: session[:user_id])
Note however that if there is no key, rails will try to fetch user from database every time you call current_user
(since @current_user
is nil). Best way to avoid it is:
def current_user
return @current_user if defined?(@current_user)
@current_user = User.find(session[:user_id])
end
This will allow you to cache nil result as well.
Upvotes: 1