Module: MultiTenant::BelongsToTenant

Defined in:
lib/multi_tenant/belongs_to_tenant.rb

Overview

Module with helpers for telling a model that it belongs to a tenant.

Defined Under Namespace

Modules: InstanceMethods

Instance Method Summary collapse

Instance Method Details

#belongs_to_tenant(association_name, scope = nil, **options) ⇒ Object

Bind this models’ records to a tenant. You must specify the association name, and you may follow it up with any of the standard ‘belongs_to’ arguments (i.e. a scope and/or an options Hash).

class Widget < ActiveRecord::Base
  belongs_to_tenant :customer
end

Parameters:

  • association_name (Symbol)

    Name of the association to the tenant

  • scope (Proc) (defaults to: nil)

    (optional) Proc holding an Arel scope for the lookup - same that the normal ‘belongs_to` method accepts.

  • options (Hash)

    (optional) Hash with association options - same that the normal ‘belongs_to` methods accepts.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/multi_tenant/belongs_to_tenant.rb', line 18

def belongs_to_tenant(association_name, scope = nil, **options)
  belongs_to association_name, scope, **options
  reflection = reflections[association_name.to_s]
  unless reflection.klass.acts_as_tenant? or reflection.klass.proxies_to_tenant?
    raise "`belongs_to_tenant :#{association_name}` failed because #{reflection.klass.name} has not used `acts_as_tenant` or `proxies_to_tenant`."
  end

  cattr_accessor :tenant_class, :tenant_foreign_key, :tenant_primary_key
  self.tenant_class = reflection.klass
  self.tenant_foreign_key = reflection.foreign_key.to_sym
  self.tenant_primary_key = reflection.association_primary_key.to_sym

  include MultiTenant::BelongsToTenant::InstanceMethods

  before_validation :assign_to_current_tenant
  validates_presence_of tenant_foreign_key
  validate :ensure_assigned_to_current_tenants

  default_scope {
    current = tenant_class.current_tenants.map(&tenant_primary_key)
    if current.size == 1
      where({tenant_foreign_key => current.first})
    elsif current.any?
      where({tenant_foreign_key => current})
    else
      where("1=1")
    end
  }
end

#belongs_to_tenant?Boolean

Returns true if this model belongs to a tenant.

Returns:

  • (Boolean)


53
54
55
# File 'lib/multi_tenant/belongs_to_tenant.rb', line 53

def belongs_to_tenant?
  respond_to? :tenant_class
end