Ruby-on-rails 如何通过会话 ID 找到设备用户?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10338692/
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
How can I find a devise user by it's session id?
提问by Geo
Given session["session_id"]is it possible to find the logged in Userto which that session belongs to?
鉴于session["session_id"]是否可以找到该User会话所属的登录?
回答by Kevin Bedell
At least on my system (rails 3.2, devise 2.0.4), you can do it like this:
至少在我的系统上(rails 3.2,devise 2.0.4),你可以这样做:
sessionis:
session是:
{"session_id"=>"be02f27d504672bab3408a0ccf5c1db5", "_csrf_token"=>"DKaCNX3/DMloaCHbVSNq33NJjYIg51X0z/p2T1VRzfY=", "warden.user.user.key"=>["User", [3], "aHFWNuz5p6fT3Z4ZvJfQq."]}
session["warden.user.user.key"][1][0], then is 3.
session["warden.user.user.key"][1][0],那么是3。
So, I'd find it as:
所以,我认为它是:
User.find(session["warden.user.user.key"][1][0])
回答by Ismael Abreu
I'm not sure what you are trying to accomplish but will try to answer
我不确定你想要完成什么,但会尝试回答
If you want only the User from the current session, a simple way would be to store his id on session, for example:
如果您只想要当前会话中的用户,一个简单的方法是将他的 id 存储在会话中,例如:
def login(username, pass)
# do the usual authentication stuff and get user
if logedin
session[:user_id] = user.id
end
end
Then get the current user would be something like
然后获取当前用户将类似于
current_user =User.find(session[:user_id])
If what you want is finding all the users that are currently logged in, I think you need to config your app to save session at DB, because predefined is that session data is store in cookies in the browser. For more information on this check this answer How to track online users in Rails?
如果您想要查找当前登录的所有用户,我认为您需要配置您的应用程序以将会话保存在数据库中,因为预定义是会话数据存储在浏览器的 cookie 中。有关此问题的更多信息,请查看此答案 How to track online users in Rails?
EDIT:Just noticed you are using devise so the first way is actually there for you. You just need to call current_usermethod at any controller.
For the second way check this answer "Who's Online" using Devise in Rails
编辑:刚刚注意到您正在使用设计,因此第一种方法实际上适合您。您只需要current_user在任何控制器上调用方法。对于第二种方式,请使用 Rails 中的设计检查此答案“谁在线”

