2

我有一个 Rails 3.2 应用程序,我想为多个客户端和一个应用程序使用一个数据库。因此,对于我创建的每个模型,我都创建了一个名为 的字段account_id,现在我想添加一个全局范围来过滤account_id日志用户的基础中的行(account_id是会话参数)。所以在初始化时我创建了一个文件并把这些代码

module ActiveRecord
  # = Active Record Named \Scopes                                                                                                                                                                                 \

  module Scoping
    module Default
      module ClassMethods

        def unscoped #:nodoc:                                                                                                                                                         
            return  (block_given? ? relation.scoping { yield } : relation).where(account_id: Thread.current['account_id'].id)

    end

        def default_scope(scope = {})
          scope = Proc.new if block_given?
          if scope.kind_of?(Array) || scope.is_a?(Hash)
              scope.merge!({:conditions=>{account_id:Thread.current['account_id'].id}})
            end
            self.default_scopes = default_scopes + [scope]
          end
        end
   end
  end
end

如果我使用用户登录account_id=2一切正常,但如果在同一时刻我登录另一个浏览器或计算机account_id=3...我有很多错误并且在日志中,我已经看到该应用程序account_id=2同时使用account_id=3

有什么解决办法吗?我该如何重写default_scope(scope = {})?其他其他想法?

4

1 回答 1

0

Thread.current[]每个请求的数据不是唯一的。我曾经有同样的问题。那时我一直在使用这个 gem https://github.com/steveklabnik/request_store。希望它会有所帮助或至少给出一个想法。

于 2017-05-25T21:24:25.780 回答