ecto 的反向多态

Inverse polymorphic with ecto

当前的 Ecto 文档 http://hexdocs.pm/ecto/Ecto.Schema.html 仅解释了如何构建 belongs_to 类型的多态关联,当多态 Comment 可以同时属于 TaskPost。但是相反的方向呢?

例如,有一个 Listing 可以具有以下四种属性之一:RoomApartmentVilaOffice .

考虑到一对一的关系,给定上面的例子,这意味着应该有 rooms_listingsapartments_listingsvila_listingsoffice_listings,这是不可能的,因为这将导致与 listings.

关联的所有其他表重复

问题是如何模拟这种关系?

我认为最简单的建模方法是翻转关联的两侧,然后将 room_id 等字段添加到 listings table:

defmodule Listing do
  use Ecto.Model
  schema "listings" do
    belongs_to :room, Room
    belongs_to :apartment, Apartment
    belongs_to :villa, Villa
    belongs_to :office, Office
  end
end

然后您可以在其他每个 table 上定义一个 has_one :listing 关系:

defmodule Room do
  use Ecto.Model
  schema "rooms" do
    has_one :listing, Listing
  end
end

defmodule Apartment do
  use Ecto.Model
  schema "apartments" do
    has_one :listing, Listing
  end
end

defmodule Villa do
  use Ecto.Model
  schema "villas" do
    has_one :listing, Listing
  end
end

defmodule Office do
  use Ecto.Model
  schema "offices" do
    has_one :listing, Listing
  end
end