使用Rails 3.2。假设我要上传10张新照片,我需要将current_user.id
与每条新记录关联起来。出于某些原因,photos_controller.rb
为空,因为它与另一个模型Shop
嵌套。这是我的代码:
class Photo < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true, :counter_cache => true
belongs_to :user, :counter_cache => true
before_create :current_user_id
before_create :associate_current_user
def current_user_id
@current_user_id ||= UserSession.find.user.id
end
private
def associate_current_user
self.user_id = @current_user_id
end
end
很明显,如果要创建10条新记录,我希望模型找到current_user
一次,然后从缓存中获取(记忆技术),但因为我正在使用{ {1}},before_create
被查询10次,而不是从缓存中获取。
我该怎么做才能缓存current_user
?
感谢。
答案 0 :(得分:0)
答案很简单:你应该不做与模型中会话相关的任何事情,它会打破MVC模式。
相反,请在您的控制器中执行此操作,因此您只需获取current_user.id
一次,然后将其分配给您的记录。
答案 1 :(得分:0)
这种逻辑属于控制器。如果您计划在其他控制器中使用此逻辑,请将current_user_id
方法移至PhotosController
(或ApplicationController
。这样,每次上传操作只会为@current_user
分配一次。
一定要把它私有化。