Makaille
Makaille

Reputation: 1666

Couldn't find User without an ID again and again

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

Answers (2)

Makaille
Makaille

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

BroiSatse
BroiSatse

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

Related Questions