module MultiTenant::BelongsToTenant::InstanceMethods

Private Instance Methods

assign_to_current_tenant() click to toggle source

Assign this model to the current tenant (if any). If there are multiple current tenants this is a no-op.

# File lib/multi_tenant/belongs_to_tenant.rb, line 63
def assign_to_current_tenant
  code_col = self.class.tenant_class.tenant_identifier
  current = self.class.tenant_class.current_tenants

  if current.size == 1 or current.map(&code_col).uniq.size == 1
    tenant_fkey = self.class.tenant_foreign_key
    if send(tenant_fkey).nil? or !current.map(&self.class.tenant_primary_key).include? send(tenant_fkey)
      current_tenant_id = self.class.tenant_class.current_tenants.first.send(self.class.tenant_primary_key)
      send "#{tenant_fkey}=", current_tenant_id
    end
  end
end
ensure_assigned_to_current_tenants() click to toggle source

If the tenant_id is set, make sure it's one of the current ones.

# File lib/multi_tenant/belongs_to_tenant.rb, line 79
def ensure_assigned_to_current_tenants
  _tenants_ids = self.class.tenant_class.current_tenants.map { |t|
    t.send(self.class.tenant_primary_key).to_s
  }
  _current_id = send self.class.tenant_foreign_key
  if _tenants_ids.any? and _current_id.present? and !_tenants_ids.include?(_current_id.to_s)
    errors.add(self.class.tenant_foreign_key, "is incorrect")
  end
end