为什么在多态关联中没有外键,例如下面表示为Rails模型的外键?
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
class Article < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Photo < ActiveRecord::Base
has_many :comments, :as => :commentable
#...
end
class Event < ActiveRecord::Base
has_many :comments, :as => :commentable
end
Run Code Online (Sandbox Code Playgroud) database ruby-on-rails foreign-key-relationship polymorphic-associations
在Phoenix中处理多态关联的推荐方法似乎是添加一个包含对其他模式的引用的中间模式:
所以,如果我想用不同种类的动物创建模式,我会这样做:
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
Run Code Online (Sandbox Code Playgroud)
但我也可以使用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 …Run Code Online (Sandbox Code Playgroud)