首页 > 解决方案 > 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_stakescexplorer.stake_address)中的表之间进行查询。

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

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

标签: ruby-on-railspostgresqlmultiple-databases

解决方案


推荐阅读