jeudi 25 mai 2017

Rails overide default scope global

I have a Rails 3.2 application, and I want to use one database for many clients and one application. So for every model I have created a field called account_id, now I want to add a global scope for filtering the row in base of the account_id of the logging user(account_id is a session params). So in initialize I have created a file and put these code

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

If I logged with user account_id=2 all is ok, but if in the same moment I logged on another browser or computer with account_id=3 ...I have many errors and on the log I have seen that the application use account_id=2 but also account_id=3 at the same time.......Any solution? How I can Rewrite default_scope(scope = {}) ? Other idea

Aucun commentaire:

Enregistrer un commentaire