简体   繁体   English

防止用户模型在Rails中多次加载

[英]Preventing user model from loading multiple times in Rails

I have a situation where the user model is used multiple times in the same query in different places. 我遇到的情况是,在同一查询中的不同位置多次使用了用户模型。 For example: I want to iterate through all the groups the users is a member of, and get a unique list of all his/her friends that are also members of these groups. 例如:我想遍历用户所属的所有组,并获得一个唯一的列表,列出他/她也是这些组成员的所有朋友。

Right now the user model gets reloaded every time, which results in: 1) Performance hit 2) Ideally I would use an instance variable to hold the unique list of friends, but I cannot do it since the user model gets reloaded. 现在,每次都会重新加载用户模型,这将导致:1)性能下降2)理想情况下,我将使用实例变量来保存唯一的好友列表,但是由于重新加载了用户模型,所以我无法这样做。

It would make a lot of sense for the user model to be global for the duration of the request - any idea how I could achieve that? 用户模型在请求期间是全局的非常有意义-知道我如何实现吗?

Assuming that with "the user model" you actually means the current user instance (the User model is used to reference the model defined bu the class User) you normally use a memoization technique. 假设使用“用户模型”实际上是指当前用户实例(用户模型用于引用通过类User定义的模型),那么通常使用记忆技术。

For instance, given you have a current_user method in your controller, you can do 例如,假设您的控制器中有current_user方法,则可以执行

def current_user
  return @current if defined?(@current)
  # In the following line load the current user. It's the first time
  # this method is requested. Further calls will return the cached instance.
  @current = ...
end

You can set a user like this: 您可以这样设置用户:

def current_user
  @current_user ||= User.find(1)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM