Rails: tracking a user's ID
Asked Answered
P

3

5

In my Rails app, I have a login page. After that person logs in, what is the best way for my app to continue tracking the person that has logged in. For example, if the user moves to different pages, my controllers/actions will lose track of that user unless I keep passing a variable between each page the user subsequently visits. Is there a better way of doing this? Should I be using the sessions variable?

Pamulapan answered 8/3, 2009 at 10:31 Comment(0)
M
7

Yes, sessions are exactly what you are looking for.

session["user_id"] = user_id

And to fetch the current user on another page (if your model is called User):

@current_user = User.find(session["user_id]")
Mintun answered 8/3, 2009 at 11:54 Comment(2)
Keep in mind that if you are using cookie based sessions, which is default I think in rails 2.1+ that this data could be changed to switch who is logged in.Otoole
Actually the cookie has a SHA512 fingerprint based on your application's secret key ensuring no tampering with the data. This means however that the cookie content is available on the client side so you should avoid storing sensitive data (passwords etc) unless you change to a server side store.Mintun
A
4

Strongly consider a plugin to manage this.

There are several, such as restful authentication.

This gives current_user and logged_in? functionality.

Antifebrile answered 8/3, 2009 at 22:25 Comment(0)
L
2

There are some great gems that do this

Lawyer answered 10/6, 2012 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.