ruby-on-rails - has_many :through across multiple databases

标签 ruby-on-rails sql-server postgresql tiny-tds

好吧,我开始写这个需要 has_many 的帮助:通过多个数据库并且仍然这样做,但我发现了一些奇怪的东西,也许我遗漏了一些东西。

所以我在做什么:

我有

rails 3.2

1 个名为 deployments 的 MSSQL 数据库表

1 个名为 reports 的 POSTGRESQL 数据库表

使用一个 POSTGRESQL 数据库表来连接被调用的关联

class Deployment < ActiveRecord::Base
  self.primary_key = :id
  establish_connection "deploy"
  self.abstract_class = true
  self.table_name = 'deployments'

  has_many :associations
  has_many :reports, through: :associations

end

class Report < ActiveRecord::Base
  self.primary_key = :id 
  belongs_to :user
  has_many :comments, dependent: :destroy

  has_many :associations
  has_many :deployments, through: :associations

  accepts_nested_attributes_for :comments, allow_destroy: true
  validates :weekending, presence: true, uniqueness: true
end

class Association < ActiveRecord::Base
  attr_accessible :deployment_id, :report_id
  belongs_to :deployment
  belongs_to :report
end

关联的创建工作正常,我在表中填充了两个 ID,但是当我尝试获取数据时,我得到以下信息:

report = Report.find(16)

report.deployments

!! #<ActiveRecord::StatementInvalid: TinyTds::Error: Invalid object name 'associations'.: EXEC sp_executesql N'SELECT [deployments].* FROM [deployments] INNER JOIN [associations] ON [deployments].[id] = [associations].[deployment_id] WHERE [associations].[report_id] = 16'>

但是,如果我以另一种方式这样做,这就是我觉得奇怪的地方:

deployment = Deployment.find('0004d1bf-c49f-4310-85cd-222806d2eb78')

deployment.reports
[#<Report id: 15, weekending: "2019-01-17", visible: true, user_id: 5, news: "asdf", created_at: "2014-05-14 02:15:05", updated_at: "2014-05-14 02:15:05">]

这是我所期望的,所以有人告诉我为什么它不能以另一种方式工作吗?

最佳答案

因为它有一个我在你的代码中看到的错误是 report.deployment 应该是

repost.deployments

所以在模型中

has_many deployments

关于ruby-on-rails - has_many :through across multiple databases,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23841265/

相关文章:

ruby-on-rails - 使用 watir-webdriver 单击文件下载弹出窗口中的按钮

ruby-on-rails - 为什么 ActiveRecord 在引发 StatementInvalid 错误后返回一个空数组?

ruby-on-rails - 在 rails 3 中形成带有 mustache 的助手

c# - 使用 Entity Framework 在 sql server 中加密/解密列

c# - 无法连接到 SQL Server session 数据库

sql - 在 SQL Server 中将特定列的值显示为标题

postgresql - 我可以使用 Heroku PG Backup 附加组件安排备份吗?

ruby-on-rails - 带 ruby​​ on rails 的多维数组

postgresql - 为什么 PostgreSQL 没有正确使用索引?

mysql - 如何使用 Rails 或原始 SQL 使用自己的时区查询多个时区的记录