rails 6 has_many 多个数据库上的关系
rails 6 has_many relation on multiple databases
我是初级 RoR 开发人员。
我有这个架构:
- 2 个数据库在不同的主机上
- 1 个应用程序在 database.yml
上设置了多个数据库
在我的第一个数据库中我存储 Vacancies
在第二个数据库中我存储 Users
空缺控制器
def create
@vacancy = Vacancy.new(vacancy_params)
ActiveRecord::Base.connected_to(database: { writing: :secondary }) do
@vacancy.save
end
end
如您所见,我在辅助数据库上使用 rails 6 activeRecord 功能进行存储。
Vacancy.rb 模型有下一个关系:
belongs_to:用户
User.rb 模型有下一个关系:
has_many :职位空缺,受抚养人: :delete_all
所以第一个数据库没有职位空缺table,第二个数据库没有用户table。
当我尝试创建 Vacancy
:
时出现此错误
Mysql2::Error: Table 'secondary.users' doesn't exist
我认为这是因为第一个数据库没有职位空缺 table 而第二个数据库没有用户 table。
我也无法为每个数据库创建任务 tables。
我该如何解决?
谢谢
对于特征 Googlers,解决方案是定义这样的关系
空缺模型
def user
ActiveRecord::Base.connected_to( database: { reading: :primary } ) do
User.where( id: user_id ).first
end
end
我不知道这是否是优雅的解决方案,但它确实有效。
我是初级 RoR 开发人员。 我有这个架构:
- 2 个数据库在不同的主机上
- 1 个应用程序在 database.yml 上设置了多个数据库
在我的第一个数据库中我存储 Vacancies
在第二个数据库中我存储 Users
空缺控制器
def create
@vacancy = Vacancy.new(vacancy_params)
ActiveRecord::Base.connected_to(database: { writing: :secondary }) do
@vacancy.save
end
end
如您所见,我在辅助数据库上使用 rails 6 activeRecord 功能进行存储。
Vacancy.rb 模型有下一个关系: belongs_to:用户
User.rb 模型有下一个关系: has_many :职位空缺,受抚养人: :delete_all
所以第一个数据库没有职位空缺table,第二个数据库没有用户table。
当我尝试创建 Vacancy
:
Mysql2::Error: Table 'secondary.users' doesn't exist
我认为这是因为第一个数据库没有职位空缺 table 而第二个数据库没有用户 table。 我也无法为每个数据库创建任务 tables。 我该如何解决?
谢谢
对于特征 Googlers,解决方案是定义这样的关系
空缺模型
def user
ActiveRecord::Base.connected_to( database: { reading: :primary } ) do
User.where( id: user_id ).first
end
end
我不知道这是否是优雅的解决方案,但它确实有效。