2017-05-25 141 views
1

我有一個Rails 3.2應用程序,我想爲許多客戶端和一個應用程序使用一個數據庫。因此,對於每個模型,我創建了一個名爲account_id的字段,現在我想添加一個全局作用域,以根據日誌記錄用戶的account_idaccount_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 = {})?其他想法?

回答

0

我有看到,我可以讓

module ActiveRecord 
    class Base 

    def self.build_default_scope #:nodoc:                                           
     super 
     default_scopes.push({:conditions=>{:account_id=>2}}) 
    end 
    end 
end 

但我有錯誤未定義的方法'合併」的#