简体   繁体   English

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

[英]How do I create an Agent model that can spans across Companies in a scope based multi tenancy app in Rails

I've built a multi-tenancy app that has User & Report that belong to a Company as shown below, (multi tenancy app using company_id to scope everything else - Users & Reports). 我已经构建了一个多租户应用程序,该应用程序具有属于Company UserReport ,如下所示(多租户应用程序使用company_id来定义其他所有内容-用户和报告)。

company.rb company.rb

class Company < ApplicationRecord
    has_many :reports
    has_many :users
end

user.rb user.rb

class User < ApplicationRecord
    belongs_to :company
    has_many :reports
end

report.rb report.rb

class Report < ApplicationRecord
    belongs_to :user
    belongs_to :company
end

I now wish to add an Agency model (with agency_users ) that will enable the to manage multiple companies (and that companies reports). 现在,我希望添加一个Agency模型(带有agency_users ),该模型将使能够管理多个公司(并且该公司进行报告)。 The Agent will need to be able to switching from one company two another. 该代理将需要能够从一家公司切换到另一家公司。

How would I approach this? 我将如何处理? Agent has many Companies 代理商有很多公司

class Agent < ApplicationRecord
    has_many :companies
end

I can't quite work out how the agent would switch between the company_ids in order to view the reports for the companies it is responsible (it's clients). 我无法完全确定代理如何在company_ids之间切换以查看其负责的公司(其客户)的报告。

Based on the comment, here's a solution that can be helpful 根据评论,这是一个可能有用的解决方案

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

Now, when the user signs in to your app, show him a dropdown of which company he's currently controlling. 现在,当用户登录到您的应用程序时,向他显示他当前控制的公司的下拉列表。 Store this id in a session and use it to query your data: 将此id存储在会话中,并用于查询数据:

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

Same goes to creating and deleting them. 创建和删除它们同样如此。

However, this is not the optimal solution (I'm not sure what your intentions are). 但是,这不是最佳解决方案(我不确定您的意图是什么)。

I would go with something more general, like user roles for each company with UserCompany having company , user and role instead of the role on the user level (maybe he's an agent at a company but admin another company; etc...). 我会采用一些更笼统的方法,例如每个公司的用户角色,而UserCompany拥有companyuserrole而不是用户级别的role (也许他是一家公司的代理人,但管理另一家公司;等等。)。 All of that varies based on what you really need to do. 所有这些都取决于您真正需要做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM