ActiveRecord :: StatementInvalid: PG :: UndefinedTable во многих отношениях, но таблица существует - PullRequest
0 голосов
/ 28 апреля 2019

У меня легкое отношение многие ко многим, и оно не работает, и я не могу понять, почему.Я уверен, что это что-то настолько очевидное ... но ..

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 голосов
/ 29 апреля 2019

Вы не можете установить ассоциации с моделью, которая хранится в другой базе данных в 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]]

Однако это не означает, что концепция осуществима.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...