Rails:访问模型中的当前用户会话(
使用 mod_passenger 维护部署在 Apache 上的 Rails v2.3.8 应用程序。
我需要访问其中一个模型中的当前用户会话(确切地说是审核员观察员)。 我知道这违反了 MVC 原则。但我必须违反它,因为我有一个观察者需要知道当前登录的用户。我有很多控制器,并且调用 Auditor 记录器不会很干燥。
我只是想能够调用 User.current 并返回当前登录的用户会话。然而,我遇到了缓存/线程安全的问题。原作者使用了一个类变量(@@current)来存储当前用户。但是这个不是线程安全的,所以我把它变成了这样
class User < AR:Base
...
def self.current
Thread.current[:user]
end
def self.current=(user)
Thread.current[:user] = user
end
...
end
所以它应该是线程安全的。在 Auditor 观察者中,我有一个调用:
Auditor(subject, action, object)
我将 User.current 作为主题传递。
这段代码在开发中效果很好,但在生产中我从 User.current 得到了错误的值。有时我会得到另一个登录用户的记录,而不是当前的记录。因此,仍然存在一些线程安全/类缓存问题,但我不知道如何修复它。
有什么建议吗? 谢谢
Maintaining a Rails v2.3.8 app deployed on Apache with mod_passenger.
I need access to current user session in one of the models (an Auditor observer to be exact).
I know this breaks the MVC principle. But i have to violate it as I have an observer that needs to know the currently logged in user. I have a lot of controllers and placing the call to Auditor logger would not be very DRY.
I'm just trying to be able to call User.current with currently logged in user session returned. However I've ran into an issue with caching/thread-safety. The original author used a class variable (@@current) to store the current user. But this is not thread safe, so I turned it into this
class User < AR:Base
...
def self.current
Thread.current[:user]
end
def self.current=(user)
Thread.current[:user] = user
end
...
end
So it should be thread-safe. And in Auditor observer I have a call:
Auditor(subject, action, object)
Where I pass in User.current as subject.
This code works great in development, but in productions I get incorrect values from User.current. At times I get another logged in user's record and not the current one. So there is some thread-safety/class-caching issue that still exists, but I can't figure out how to fix it.
Any suggestions?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ActiveRecord 和 ActionPack 完全不同,因此您无法访问模型中的会话/cookie。如果您需要当前用户,您有两个选择。
模型
选项 1 - 将当前用户传递给控制器中的
:选项 2 - 拥有一个在修改用户对象后执行操作的用户模型。
在您的用户模型中:
ActiveRecord and ActionPack are completely different so you do not have access to session/cookies in models. If you need the current user you have two options.
Option 1 - Pass the current user to the model
In your controller:
Option 2 - Have a user model that performs action after a user object is modified.
In your user model: