Get current user id in devise

2019-04-21 08:09发布

问题:

How do I Get the current user id in my controller using devise?

In my controller I have something like this:

def index

me = current_user
c = User.find(me)
@sheets = c.time_sheets
end

I am getting an error say that "Couldn't find User without an ID".

If If I put in a static number in the User.find() it works but of course that is not what I want. Any help would be greatly appreciated.

thanks!

回答1:

Replace current index action as below

def index    
   if current_user
     @sheets = current_user.time_sheets
   else
     redirect_to new_user_session_path, notice: 'You are not logged in.'
   end
end

If user is not logged in, i.e., current_user=nil then user would be redirected to login page with a flash message.