首页 > 解决方案 > 如何在 Rails 中基于范围的多租户应用程序中创建可以跨公司的代理模型

问题描述

我已经构建了一个具有User&的多租户应用程序,Report它属于 a Company,如下所示(使用 company_id 来确定其他所有内容的多租户应用程序 - 用户和报告)。

公司.rb

class Company < ApplicationRecord
    has_many :reports
    has_many :users
end

用户.rb

class User < ApplicationRecord
    belongs_to :company
    has_many :reports
end

报告.rb

class Report < ApplicationRecord
    belongs_to :user
    belongs_to :company
end

我现在希望添加一个Agency模型(带有agency_users),它可以管理多个公司(以及公司报告)。代理将需要能够从一家公司切换到另一家公司。

我将如何处理这个?代理有多家公司

class Agent < ApplicationRecord
    has_many :companies
end

我不太清楚代理如何在 company_id 之间切换以查看它负责的公司(它是客户)的报告。

标签: ruby-on-railsmulti-tenantruby-on-rails-5.1

解决方案


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

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)例如;

创建和删除它们也是如此。

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

我会选择更通用的东西,比如每个公司的用户角色UserCompanycompanyuser不是role用户role级别的(也许他是一家公司的代理人,但管理另一家公司;等等)。所有这些都取决于您真正需要做的事情。


推荐阅读