我有一个Rails 3.2应用程序,我想为许多客户端和一个应用程序使用一个数据库。因此,对于每个模型,我创建了一个名为account_id
的字段,现在我想添加一个全局作用域,以根据日志记录用户的account_id
(account_id
是会话参数)进行过滤。因此,在初始化我创建了一个文件,并把这些代码Rails覆盖默认范围全局
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 = {})
?其他想法?