ActiveRecord :: StatementInvalid:PG :: UndefinedTable存在多对多关系,但表存在

时间:2019-04-28 08:36:07

标签: ruby-on-rails activerecord

我有一个简单的多对多关系,这是行不通的,我不明白为什么。我敢肯定这很明显...但是..

class Content < ApplicationRecord
  has_many                :content_brands
  has_many                :brands,                  through:    :content_brands
end

class ContentBrand < ApplicationRecord
  belongs_to :content
  belongs_to :brand
end

class Brand < ApplicationRecord
  establish_connection Rails.application.config.brands_database_configuration

  has_many :content_brands
  has_many :contents, through: :content_brands
end

但是

irb(main):002:0> Content.first.brands
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERRORE:  la relazione "content_brands" non esiste
LINE 1: SELECT  "brands".* FROM "brands" INNER JOIN "content_brands"...
                                                    ^
: SELECT  "brands".* FROM "brands" INNER JOIN "content_brands" ON "brands"."id" = "content_brands"."brand_id" WHERE "content_brands"."content_id" = $1 ORDER BY "brands"."name" ASC LIMIT $2

该表存在,我可以查询

irb(main):006:0> ContentBrand.first.brand
  ContentBrand Load (0.5ms)  SELECT  "content_brands".* FROM "content_brands" ORDER BY "content_brands"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Brand Load (27.4ms)  SELECT  "brands".* FROM "brands" WHERE "brands"."id" = $1 ORDER BY "brands"."name" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
=> #<Brand id: 1, name: "Nokia", logo: "nokia.jpeg", created_at: "2016-12-08 15:50:48", updated_at: "2017-02-02 15:51:43", web_site: "http://www.nokia.it">

为什么?

我发疯了,因为逆向关系有效

Brand.first.contents
  Brand Load (25.8ms)  SELECT  "brands".* FROM "brands" ORDER BY "brands"."name" ASC LIMIT $1  [["LIMIT", 1]]
  Content Load (0.7ms)  SELECT  "contents".* FROM "contents" INNER JOIN "content_brands" ON "contents"."id" = "content_brands"."content_id" WHERE "content_brands"."brand_id" = $1 ORDER BY "contents"."published_at" DESC LIMIT $2  [["brand_id", 391], ["LIMIT", 11]]
=> #<ActiveRecord::Associations::CollectionProxy []>
irb(main):011:0>

更新:我忘了告诉你品牌在另一个数据库上...

1 个答案:

答案 0 :(得分:0)

您无法设置与存储在ActiveRecord的另一个数据库中的模型的关联。这是有道理的,因为您无法在Postgres中的单个查询中加入另一个数据库,而不会跳过一些非常严重的问题(Postgres_FDW)。而且由于ActiveRecord具有多语言特性,对于非常有限的用例而言,这将是非常复杂的事情。

如果有可能,我将切换到单个数据库设置,即使这意味着您必须复制数据。

如果您查看“反向查询”,您会发现它有效,因为它不是一个查询:

  # queries the "brands" database
  Brand Load (25.8ms)  SELECT  "brands".* FROM "brands" ORDER BY "brands"."name" ASC LIMIT $1  [["LIMIT", 1]]

  # queries your main database
  Content Load (0.7ms)  SELECT  "contents".* FROM "contents" INNER JOIN "content_brands" ON "contents"."id" = "content_brands"."content_id" WHERE "content_brands"."brand_id" = $1 ORDER BY "contents"."published_at" DESC LIMIT $2  [["brand_id", 391], ["LIMIT", 11]]

但这并不意味着该概念可行。