记住当前用户对象before_create

时间:2012-12-01 13:56:39

标签: ruby-on-rails

使用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

感谢。

2 个答案:

答案 0 :(得分:0)

答案很简单:你应该做与模型中会话相关的任何事情,它会打破MVC模式。

相反,请在您的控制器中执行此操作,因此您只需获取current_user.id一次,然后将其分配给您的记录。

答案 1 :(得分:0)

这种逻辑属于控制器。如果您计划在其他控制器中使用此逻辑,请将current_user_id方法移至PhotosController(或ApplicationController。这样,每次上传操作只会为@current_user分配一次。

一定要把它私有化。