Given session["session_id"]
is it possible to find the logged in User
to which that session belongs to?

- 93,257
- 117
- 344
- 520
-
You can use User.current_user instead... did you tried? – Victor Rodrigues Apr 26 '12 at 18:06
3 Answers
At least on my system (rails 3.2, devise 2.0.4), you can do it like this:
session
is:
{"session_id"=>"be02f27d504672bab3408a0ccf5c1db5", "_csrf_token"=>"DKaCNX3/DMloaCHbVSNq33NJjYIg51X0z/p2T1VRzfY=", "warden.user.user.key"=>["User", [3], "$2a$10$5HFWNuz5p6fT3Z4ZvJfQq."]}
session["warden.user.user.key"][1][0]
, then is 3
.
So, I'd find it as:
User.find(session["warden.user.user.key"][1][0])

- 13,254
- 10
- 78
- 114
-
11On Rails 4.2.1, Devise 3.4.1 you'll want to use User.find(session["warden.user.user.key"][0][0]) – Razi Shaban Apr 06 '15 at 05:02
-
Thanks. This example is ugly, but it work. Thanks again. This example for cookies: http://stackoverflow.com/a/43549108/5754223 – artamonovdev Apr 21 '17 at 17:51
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:
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?
EDIT: Just noticed you are using devise so the first way is actually there for you. You just need to call current_user
method at any controller.
For the second way check this answer "Who's Online" using Devise in Rails

- 1
- 1

- 16,443
- 6
- 61
- 75
And i might add this, as i was trying to do it the other way, if you are using ActiveRecord session_store you can find all stored sessions of a user like so:
ActiveRecord::SessionStore::Session.select{ |s| s.data["warden.user.user.key"] && s.data["warden.user.user.key"][0][0] == user_id }

- 124
- 2
- 3