我遇到的情况是,用户模型在不同位置的同一查询中多次使用。例如:我想遍历用户所属的所有组,并获得他/她的所有朋友的唯一列表,这些朋友也是这些组的成员。
现在每次都会重新加载用户模型,这会导致: 1)性能受到影响 2)理想情况下,我会使用一个实例变量来保存唯一的朋友列表,但是我不能这样做,因为用户模型被重新加载。
在请求期间,用户模型是全局的很有意义 - 任何想法我怎么能实现这一点?
答案 0 :(得分:0)
假设使用“用户模型”实际上意味着当前用户实例(用户模型用于引用由用户类定义的模型),通常使用记忆技术。
例如,假设您的控制器中有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
答案 1 :(得分:0)
您可以像这样设置用户:
def current_user
@current_user ||= User.find(1)
end