【发布时间】:2018-08-25 23:15:52
【问题描述】:
在 Phoenix 中处理多态关联的推荐方法似乎是添加一个包含对其他模式的引用的中间模式:
- Inverse polymorphic with ecto
- https://hexdocs.pm/ecto/Ecto.Schema.html#belongs_to/3-polymorphic-associations)。
所以如果我想用不同种类的动物创建模式,我会这样做:
defmodule Animal do
use Ecto.Model
schema "animals" do
belongs_to(:dog, Dog)
belongs_to(:cat, Cat)
belongs_to(:owner, PetOwner)
end
end
defmodule Dog do
use Ecto.Model
schema "dogs" do
end
end
defmodule Cat do
use Ecto.Model
schema "cats" do
end
end
defmodule PetOwner do
use Ecto.Model
schema "pet_owners" do
has_one(:pet, Animal)
end
end
但我也可以拥有包含二进制字段和类型的 PetOwner 模式:
defmodule Dog do
use Ecto.Model
schema "dogs" do
end
end
defmodule Cat do
use Ecto.Model
schema "cats" do
end
end
defmodule PetOwner do
use Ecto.Model
schema "pet_owners" do
field(:pet, :binary)
field(:pet_type, :integer)
end
end
或者甚至只是对所有者模式中的所有动物有一个可为空的引用:
defmodule Dog do
use Ecto.Model
schema "dogs" do
belongs_to(:owner, PetOwner)
end
end
defmodule Cat do
use Ecto.Model
schema "cats" do
belongs_to(:owner, PetOwner)
end
end
defmodule PetOwner do
use Ecto.Model
schema "pet_owners" do
has_one(:cat, Cat)
has_one(:dog, Dog)
end
end
第一种方法似乎增加了模式的复杂性。不同方法的优缺点是什么?
编辑:假设宠物主人只能拥有一只宠物,如果架构允许多只宠物,则验证在变更集中完成。
【问题讨论】:
-
我可能会选择最后一个。没有额外的复杂性,不会失去完整性并且简单明了。
标签: elixir phoenix-framework polymorphic-associations ecto