我在这里找到了一篇不错的读物https://rubygarage.org/blog/separating-features-in-a-multi-tenant-saas-app
生成租户、功能和订阅模型
rails g 模型租户名称:字符串子域:字符串
rails g 模型功能名称:字符串
rails g 模型订阅租户:参考功能:参考
rake db:迁移
修改租户模型 app/models/tenant.rb
class Tenant < ApplicationRecord
has_many :subscriptions
has_many :features, through: :subscriptions
end
修改特征模型 app/models/feature.rb
class Feature < ApplicationRecord
has_many :subscriptions
has_many :tenants, through: :subscriptions
end
修改订阅模型 app/models/subscription.rb
class Subscription < ApplicationRecord
belongs_to :tenant
belongs_to :feature
end
使用 FeatureToggle 类创建一个新文件 app/models/feature_toggle.rb
class FeatureToggle
def initialize
@tenant_features = []
end
def for(tenant)
@tenant_features = tenant.features.pluck(:name) if tenant
end
def on?(feature_name)
@tenant_features.include?(feature_name)
end
end
修改 app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :current_tenant
helper_method :feature_toggle
def current_tenant
@current_tenant ||= Tenant.find_by_subdomain(request.subdomain)
end
def feature_toggle
@feature_toggle ||= FeatureToggle.new.tap do |ft|
ft.for current_tenant
end
end
end