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