rails 4 中的多个数据库连接

Multiple database connection in rails 4

我在 Rails 4 应用程序中实现多个数据库连接时遇到了麻烦。除了主数据库连接,我还通过在 database.yml.

中指定详细信息创建了辅助连接
secondary_base:
 adapter: postgresql
 encoding: unicode
 host: localhost
 database: secondary_db
 pool: 5
 username: postgres
 password: postgres

然后创建了一个名为 SecondaryBase 的模型,它保存与该辅助数据库的连接。代码如下:

secondary_base.rb

class SecondaryBase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "secondary_base"
end

然后添加了两个模型MemberSubdomain

member.rb

class Member < SecondaryBase
  has_and_belongs_to_many :subdomains
end

subdomain.rb

class Subdomain < SecondaryBase
  has_and_belongs_to_many :members
end

现在您可以看到 MemberSubdomain 模型通过 has_and_belongs_to_many 关系关联。因此,当我尝试将数据插入名为 members_subdomains 的连接 table 时,它现在正在工作并给我类似 PG: Undefined table 的错误,尽管 table 退出secondary_db 数据库。据我了解,当我在 Rails 3.2.13 中尝试相同的代码时,rails 试图在主 database.But 中找到 members_subdomains table,然后有一点问题都没有,一切都很好。你们中有人处理过类似的问题吗?请帮助。

我相信您需要从 has_and_belongs_to_many 切换到 has_many :through 才能使其正常工作。为此,只需为连接创建一个模型 table - 我将其称为“MemberSubdomain”。

class SecondaryBase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "secondary_base"
end

class MemberSubdomain < SecondaryBase
  self.table_name = 'members_subdomains'
end

class Member < SecondaryBase
  has_many :member_subdomains
  has_many :subdomains, :through => :member_subdomains, :source => :subdomain
end

class Subdomain < SecondaryBase
  has_many :member_subdomains
  has_many :members, :through => :member_subdomains, :source => :member
end