【问题标题】:Get current user id in devise在设计中获取当前用户ID
【发布时间】:2023-03-06 23:03:01
【问题描述】:

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

在我的控制器中,我有这样的东西:

def index

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

我收到一条错误消息,提示“找不到没有 ID 的用户”。

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

谢谢!

【问题讨论】:

  • @sheets = me.time_sheets
  • 你确定你已经登录了吗? User.find(current_user) 应该重新加载当前用户,而不是引发该错误。
  • User.find(params[:id]);是您可能正在寻找的,甚至是当前用户

标签: ruby-on-rails ruby-on-rails-4 devise


【解决方案1】:

如下替换当前索引操作

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

如果用户未登录,即 current_user=nil,则用户将被重定向到登录页面,并显示一条消息。

【讨论】:

  • 谢谢!!!!!!那行得通。之前是不是因为 devise 无法确定是否有用户登录而无法正常工作?
  • 很高兴为您提供帮助。:) Devise 只会在登录时设置current_user,否则current_user 将为零。
猜你喜欢
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
  • 2017-04-26
  • 2015-06-01
相关资源
最近更新 更多