【问题标题】:has_many :through across multiple databaseshas_many :通过多个数据库
【发布时间】:2014-05-24 15:34:40
【问题描述】:

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

所以我在做什么:

我有

Rails 3.2

1 个名为部署的 MSSQL DB 表

1 个名为报告的 POSTGRESQL DB 表

使用 POSTGRESQL DB 表加入称为关联

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">]

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

【问题讨论】:

  • 你如何向 rails 表明这些表在不同的 rdbms 上?因为它认为他们在那个失败的查询中在一起。
  • @Richard,我只是使用建立连接“部署”
  • 我在看一个叫做 st-elsewhere 的宝石,但它已经在 5 年内被触摸了
  • 为同一个应用程序拥有 2 个数据库服务器肯定会导致灾难。
  • @Alexandros 很有帮助,但有些事情是无能为力的 :(

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


【解决方案1】:

由于它是一个错误,我在您的代码中看到的是 report.deployment 应该是

repost.deployments

所以在模型中

has_many deployments

【讨论】:

  • 很抱歉只是写这个的时候打错了,就是代码里是这样的
  • 我现在明白了,我注意到您在 find 中使用的 id 不是标准 id,并且您的关系中没有外键来将其映射到新的,因此 rails 正在尝试将 '0004d1bf-c49f-4310-85cd-222806d2eb78' 放入原始 int 列。告诉我这是否解决了它。
  • 我已经改变了一些东西并得到了一点进一步,但又开始了另一个问题 - link
猜你喜欢
  • 2012-01-08
  • 2018-12-20
  • 1970-01-01
  • 2016-04-24
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 2017-12-14
  • 1970-01-01
相关资源
最近更新 更多