Module: MultiTenant::ModelExtensions::ClassMethods

Defined in:
lib/activerecord-multi-tenant/multi_tenant.rb

Instance Method Summary collapse

Instance Method Details

#multi_tenant(tenant, options = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/activerecord-multi-tenant/multi_tenant.rb', line 47

def multi_tenant(tenant, options = {})
  # Provide fallback primary key setting to ease integration with the typical Rails app
  self.primary_key = 'id' if primary_key.nil?

  # Typically we don't need to run on the tenant model itself
  if to_s.underscore.to_sym != tenant
    belongs_to(tenant)
    acts_as_tenant(tenant, options)

    around_save -> (record, block) { persisted? ? MultiTenant.with_id(record.public_send(tenant.to_s + '_id')) { block.call } : block.call }
    around_update -> (record, block) { MultiTenant.with_id(record.public_send(tenant.to_s + '_id')) { block.call } }
    around_destroy -> (record, block) { MultiTenant.with_id(record.public_send(tenant.to_s + '_id')) { block.call } }
  end

  # Workaround for https://github.com/citusdata/citus/issues/687
  if to_s.underscore.to_sym == tenant
    before_create -> { self.id ||= self.class.connection.select_value("SELECT nextval('" + [self.class.table_name, self.class.primary_key, 'seq'].join('_') + "'::regclass)") }
  end
end