【问题标题】:Handle an Option in Rails Controller在 Rails 控制器中处理选项
【发布时间】:2019-09-07 06:45:45
【问题描述】:

我有一个引擎想成为单租户,但可以选择处理多租户。有没有更好的方法可以处理这个问题?还是下面的例子可以接受?

def index
  if defined?multi_tenant_setting
    @script_extensions = Script::Extension.where(org_id: current_user.org_id)
  else
    @script_extensions = Script::Extension.all
  end
end

【问题讨论】:

    标签: ruby-on-rails model-view-controller controller


    【解决方案1】:

    我在这里找到了一篇不错的读物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
    

    【讨论】:

    • 谢谢,这将使我朝着正确的方向前进。对卡在多租户插件上的奖金 b/c 投票赞成。非常感谢:)
    猜你喜欢
    • 2012-12-16
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    相关资源
    最近更新 更多