ruby-on-rails - Rails:使用数据库前缀不起作用 - 使用多个数据库连接表查询
问题描述
我想has_many to has_many
在两个不同数据库中的两个表之间建立关联。
这是模型:
class UserStake < ApplicationRecord
#connects to local default database `swan_db_sync`
belongs_to :user
belongs_to :stake_address
self.table_name = "#{self.connection.current_database}.user_stakes"
end
class User < ApplicationRecord
#connects to local default database `swan_db_sync`
has_many :user_stakes
has_many :stake_addresses, through: :user_stakes
end
class StakeAddress < DbSyncRecord
#connects to a remote database `cexplorer` (see below)
self.table_name = "#{self.connection.current_database}.stake_address"
has_many :user_stakes
has_many :users, through: :user_stakes
end
class DbSyncRecord < ActiveRecord::Base
self.abstract_class = true
establish_connection DB_SYNC_DB
end
但是这个设置不起作用,事实上即使是带有数据库前缀的普通查询也不起作用:
2.6.1 :003 > StakeAddress.first
Traceback (most recent call last):
1: from (irb):3
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: relation "cexplorer.stake_address" does not exist)
LINE 1: SELECT "cexplorer"."stake_address".* FROM "cexplorer"."stake...
2.6.1 :004 > UserStake.first
Traceback (most recent call last):
2: from (irb):4
1: from (irb):4:in `rescue in irb_binding'
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: relation "swan_db_sync.user_stakes" does not exist)
LINE 1: SELECT "swan_db_sync"."user_stakes".* FROM "swan_db_sync"."u...
我会认为该表"swan_db_sync.user_stakes"
存在。表的前缀user_stakes
应该表明它来自的数据库 ( swan_db_sync
)。指示数据库将允许我JOIN TABLE
在不同数据库(swan_db_sync.user_stakes
和cexplorer.stake_address
)中的表之间进行查询。
然而,当我只为一张表上的查询指定数据库前缀时,Rails 查询甚至找不到一张表。
我究竟做错了什么?如何在表查询中指定数据库?
解决方案
推荐阅读
- c - 如何在 o(1) 空间复杂度中合并两个排序数组?
- reactjs - 我应该在 React.js 中加密本地存储吗?
- python - 我如何在python中正确调用这个函数?
- javascript - 使用来自服务器的数据填充 Angular 的响应式表单
- reactjs - 如何使用 typescript 扩展 React 库命名空间
- c++ - 使用 string.length() 作为 for 循环的结尾时,C++ 字符串订阅超出范围
- iis - IIS/Pool/Web API / 池下的第一个请求需要很长时间
- java - Java AES GCM javax.crypto.AEADBadTagException:标签不匹配
- c# - CSV 助手。如何在扩展方法中调用 MemberMap 的 ConvertUsing?
- r - 如何在r中找到第一次观察和前两个连续负面观察之间的观察次数