Module: MultiTenant::ActsAsTenant::TenantSetters

Defined in:
lib/multi_tenant/acts_as_tenant.rb

Overview

Class methods applied to the tenant model.

class Client < ActiveRecord::Base
  acts_as_tenant using: :code
end

Client.current
=> # the current client set by the middleware, or nil

# Manually set the current client, where 'acme' is in the 'code' col in the db
Client.current = 'acme'

# Manually set the current client to an AR record
Client.current

Instance Method Summary collapse

Instance Method Details

#current_tenant=(record_or_identifier) ⇒ Object Also known as: current=

Set the current tenant record. You may either pass an ActiveRecord Client record, OR the value of the ‘:using` option you passed to `acts_as_tenant`. Thread-safe.

Parameters:

  • record_or_identifier

    the record or the identifier in the ‘tenant_identifier’ column.



94
95
96
# File 'lib/multi_tenant/acts_as_tenant.rb', line 94

def current_tenant=(record_or_identifier)
  self.current_tenants = Array(record_or_identifier)
end

#current_tenants=(records_or_identifiers) ⇒ Object

Set the array of current tenant records. You may either pass an ActiveRecord Client record, OR the value of the ‘:using` option you passed to `acts_as_tenant`. Thread-safe.

Parameters:

  • records_or_identifiers

    array of the records or identifiers in the ‘tenant_identifier’ column.



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/multi_tenant/acts_as_tenant.rb', line 105

def current_tenants=(records_or_identifiers)
  records, identifiers = Array(records_or_identifiers.uniq).partition { |x|
    x.class.respond_to?(:table_name) && x.class.table_name == self.table_name
  }
  tenants = if identifiers.any?
              queried_records = where({tenant_identifier => identifiers}).to_a
              if queried_records.size < identifiers.size and raise_on_tenant_not_found
                raise ::MultiTenant::TenantsNotFound.new(self, identifiers, queried_records)
              end
              records + queried_records
            else
              records
            end
  Thread.current.thread_variable_set tenant_thread_var, tenants
end