In Multi-tenant architecture by using single instance it serves multiple accounts. Each account is called a tenant.
There are so many different approaches to implement multi-tenancy architecture using traditional or by using any gems. By comparing all those I found the simplest way of implementing Multi-tenancy that is with “Act as tenant” gem
Representation of Gem
gem 'acts_as_tenant'
After placing this in your gem file run bundle to install this.
Usage:
It sets the current tenant by using subdomain and adds the ability to scope models to a tenant.
For setting current tenant place the below code in your application controller
Creating Tenant Account Model
class AddcolumnsToAccounts < ActiveRecord::Migration
def up
add_column :accounts, :sub_domain, :string
end
end
set_current_tenant_by_subdomain(:account, :subdomain)
Manual approach to set current tenant
class ApplicationController < ActionController::Base
set_current_tenant_through_filter
before_filter :find_the_current_tenant
def find_the_current_tenant
current_account = Account.find_by_subdomain(subdomain: 'subdomain')
set_current_tenant(current_account)
end
end
Scoping your models
class AddAccountToColleges < ActiveRecord::Migration
def up
add_column :colleges, :account_id, :integer
add_index :colleges, :account_id
end
end
class College < ActiveRecord::Base
acts_as_tenant(:account)
end
Acts as tenant adds a method to validate uniqueness, validates_uniqueness_to_tenant
If you need to validate for uniqueness, you can do by using following code:
validates_uniqueness_to_tenant :title
And more over default rails validates_uniqueness_of are also available.
For specifying foreign key use the following syntax
acts_as_tenant(:account, :foreign_key => 'AccountID')
by default it takes account_id
Configuración
An initializer can be created to control option in ActsAsTenant. You can change the configuration options in config/initializers/acts_as_tenant.rb
ActsAsTenant.configure do |config|
config.require_tenant = false
end
config.require_tenant when set to true will raise an ActsAsTenant::NoTenant error whenever a query is made without a tenant set.
Source : https://github.com/ErwinM/acts_as_tenant
Suscríbete para recibir las últimas actualizaciones
Artículos Relacionados