Rails:跟踪用户的ID

时间:2022-12-05 13:00:52

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?

在我的Rails应用程序中,我有一个登录页面。在该人登录后,我的应用程序继续跟踪已登录的人的最佳方式是什么。例如,如果用户移动到不同的页面,我的控制器/操作将失去对该用户的跟踪,除非我继续通过用户随后访问的每个页面之间的变量。有更好的方法吗?我应该使用sessions变量吗?

3 个解决方案

#1


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):

并在另一个页面上获取当前用户(如果您的模型名为User):

@current_user = User.find(session["user_id]")

#2


4  

Strongly consider a plugin to manage this.

强烈考虑一个插件来管理它。

There are several, such as restful authentication.

有几种,例如restful authentication。

This gives current_user and logged_in? functionality.

这给出了current_user和logged_in?功能。

#3


2  

There are some great gems that do this

有一些很棒的宝石可以做到这一点

#1


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):

并在另一个页面上获取当前用户(如果您的模型名为User):

@current_user = User.find(session["user_id]")

#2


4  

Strongly consider a plugin to manage this.

强烈考虑一个插件来管理它。

There are several, such as restful authentication.

有几种,例如restful authentication。

This gives current_user and logged_in? functionality.

这给出了current_user和logged_in?功能。

#3


2  

There are some great gems that do this

有一些很棒的宝石可以做到这一点