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 TABLEswan_db_sync.user_stakes)中的表之间执行 cexplorer.stake_address 查询

然而,当我只在一张表上为查询指定数据库前缀时,Rails 查询甚至找不到一张表。

我做错了什么?如何在表查询中指定数据库

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)