我有一个 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 = {})
?其他其他想法?