ruby on Rails:在不同模型上存储 current_user 的数据

发布于 2024-08-11 13:00:58 字数 172 浏览 1 评论 0原文

我正在尝试使用 attr_accessor :offset 将 current_user 的数据存储在用户模型中。我想使用 current_user 模型中存储的偏移量来获取不同模型的记录。当我从不同的模型更改此偏移时,它不会保存它吗?

我觉得数据库专栏对于offest来说是多余的。该偏移量将为 0..n 整数。

I am trying to store data from the current_user in a User model with attr_accessor :offset. I would like to fetch records of a different model using the offset stored in the current_user model. When I change this offset from a different model it does not save it?

I feel a database Column for the offest is overkill. This offset would be 0..n integer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风吹雨成花 2024-08-18 13:00:58

假设我正确理解了您的问题:

数据库列实际上是数据在重新加载后保留在模型中的唯一方法。 current_user 变量通过将其存储在控制器和视图的会话中来解决这个问题。无论您在何处尝试使用 current_user,我都觉得您的问题源于将 current_user 从一个请求传递到下一个请求的方法,您对 current_user 所做的任何更改都不会延续到下一个请求。

current_user id 存储在登录时的会话哈希中。第一次调用 current_user 作为控制器操作的一部分时,authentiated_system 模块会根据会话哈希中的 id 查找用户。这意味着您对 current_user 所做的任何更改都会丢失,除非您在控制器操作完成之前保存它。数据库列是做到这一点的唯一方法。

不过,您可以完全忽略当前用户,并使用 session[:offset] = offset 将偏移量添加到会话哈希中。以同样的方式在您的控制器/视图中引用它。只要您的用户不结束浏览会话,session[:offset] 就会返回您尝试保留的偏移值。

但是,如果偏移量将成为应在登录会话之间持续存在的用户首选项,那么它确实作为数据库列属于您的用户模型。

Assuming I understood your question correctly:

A database column is really the only way for data to persist in a model beyond a reload. The current_user variable gets around this by storing it in the sessions for your controllers and views. Regardless of where you're trying to use current_user, I have the feeling your problem stems from the method that current_user is passed from one request to the next, any changes you make to current_user will not carry over to the next request.

The current_user id is stored in the session hash at login. The first time you call current_user as part of a controller action the authenticated_system module finds the User based on the id in the session hash. Meaning any changes you make to current_user are lost unless you save it before the controller action finishes. A database column is the only way to do that.

However you can ignore the current user entirely and add offset to the session hash, with session[:offset] = offset. Refer to it in your controllers/views the same way. So long as your user doesn't end their browsing session session[:offset] will return the offset value you're trying to keep.

But, if offset is going to be a user preference that should persist between login sessions, then it really does belong in your user model as a database column.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文