使用 Apartment Gem 在 rails 中添加排除模型和非排除模型之间的关联

问题描述

我正在为每个租户创建具有单独数据库的多租户应用程序,我有通用(排除)模型,即组织,其他非排除模型是用户、课程,3 个模型之间的关联如下

class Organisation < ApplicationRecord
   has_many :users
   has_many :posts
end

class User < ApplicationRecord
   belongs_to :organisation
end

class Post < ApplicationRecord
   belongs_to :organisation
end

在apartment.rb文件中包含以下代码

Apartment.configure do |config|
  config.excluded_models = %w{ "Organisation" }
end

当我使用组织标识(外键)创建用户时,它会给出错误(约束违反错误(组织标识)

如何使用多租户数据库解决此问题,或者有什么方法可以在每个租户数据库中创建组织记录(排除模型记录)的副本。

提前致谢

解决方法

来自多个数据库的两个表之间的关联是不可能的。 如果您使用的是公寓 gem,则创建一个通用模块并在公寓配置文件中排除此通用模块并创建新数据库以保持关联正常工作 例如

class Tenant
  # common module
end
class User
end
class Address
end