在模型中访问current_user的问题

时间:2012-03-15 19:51:54

标签: ruby-on-rails-3 observer-pattern

关于这个问题有很多问题,“如何在模型中访问current_user”,我尝试了一些,最后做了“老方法”,设置

 cattr_accessor :current_user

在我的 FeedObserver 中,然后设置

FeedObserver.current_user = current_user
带有before_filter的 ApplicationController 中的

不幸的是,它似乎没有按预期工作,有时在FeedObserver中使用了不同的用户。

我正在使用rails 3.2.2,ruby 1.9.3p0,nginx,unicorn。我无法解释这种行为,因为 before_filter应该为每个请求设置current_user,不应该被其他用户覆盖......?

class FeedObserver < ActiveRecord::Observer
  cattr_accessor :current_user
  observe :account, :user

  def after_create(ressource)
    log!(ressource)
  end

  def log!(ressource, event_name)
    feed_item = FeedItem.new(
      user: current_user,
      data: ressource.changes,
      account_id: current_user.account.id
    )
    feed_item.save if feed_item.valid?
  end
end

2 个答案:

答案 0 :(得分:0)

我推荐sentient_user宝石用于您的目的

答案 1 :(得分:0)

不确定导致错误的原因,我想这只是覆盖变量的并发请求。正如@Andrei建议我尝试了sentient_user gem。但sentient_user有同样的问题,可以解决:

  module SentientController
    def self.included(base)
      base.class_eval {
        around_filter do |controller, action|
          User.current = controller.send(:current_user)
          begin
            action.call
          ensure
            User.current = nil
          end      
        end
      }
    end
  end

修复了线程泄漏问题......

相关问题