如何在Rails中基于范围的多租户应用程序中创建可跨公司的代理模型

时间:2019-01-09 11:58:34

标签: ruby-on-rails multi-tenant ruby-on-rails-5.1

我构建了一个多租户应用,该应用具有User的{​​{1}}和Report,如下所示,(多租户应用使用company_id来定义其他所有对象-用户和报告)。

company.rb

Company

user.rb

class Company < ApplicationRecord
    has_many :reports
    has_many :users
end

report.rb

class User < ApplicationRecord
    belongs_to :company
    has_many :reports
end

我现在希望添加一个class Report < ApplicationRecord belongs_to :user belongs_to :company end 模型(带有Agency),该模型将使能够管理多个公司(该公司进行报告)。该代理将需要能够从一家公司切换到另一家公司。

我将如何处理?代理商有很多公司

agency_users

我无法完全确定代理商如何在company_id之间切换以便查看其负责的公司(其客户)的报告。

1 个答案:

答案 0 :(得分:0)

根据评论,这是一个可能有用的解决方案

class Agency < ApplicationRecord
  has_many :companies
  has_many :users
end

class Company < ApplicationRecord
    has_many :reports
    belongs_to :agency
end

class Users < ApplicationRecord
    has_many :reports
    belongs_to :agency
    enum role: [:agent]
end

现在,当用户登录到您的应用程序时,向他显示他当前控制的公司的下拉列表。将此id存储在会话中,并使用它来查询您的数据:

current_user.reports.where(company_id: session[:company_id].to_i)

创建和删除它们相同。

但是,这不是最佳解决方案(我不确定您的意图是什么)。

我会采用一些更通用的方法,例如每个公司的UserCompany具有companyuserrole而不是role的用户角色用户级别(也许他是一家公司的代理人,但管理另一家公司;等等...)。所有这些都取决于您真正需要做的事情。