module MultiTenant::BelongsToTenant

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

Public Instance Methods

belongs_to_tenant(association_name, scope = nil, **options) click to toggle source

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

@param association_name [Symbol] Name of the association to the tenant @param scope [Proc] (optional) Proc holding an Arel scope for the lookup - same that the normal `belongs_to` method accepts. @param options [Hash] (optional) Hash with association options - same that the normal `belongs_to` methods accepts.

# 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?() click to toggle source

Returns true if this model belongs to a tenant.

@return [Boolean]

# File lib/multi_tenant/belongs_to_tenant.rb, line 53
def belongs_to_tenant?
  respond_to? :tenant_class
end