Ruby-on-rails 在设计中获取当前用户 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22106742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:24:50  来源:igfitidea点击:

Get current user id in devise

ruby-on-railsruby-on-rails-4devise

提问by mild0d

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

如何使用 devise 在我的控制器中获取当前用户 ID?

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".

我收到一条错误消息,说“找不到没有 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.

如果我在 User.find() 中输入一个静态数字,它会起作用,但这当然不是我想要的。任何帮助将不胜感激。

thanks!

谢谢!

回答by Kirti Thorat

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.

如果用户未登录,即 current_user=nil 则用户将被重定向到带有闪现消息的登录页面。