2016-04-11 39 views
3

在Ecto遷移中實現引用自己表的外鍵的正確方法是什麼?Elixir Ecto:我如何創建一個自引用外鍵?

例如我想創建一個表,其中任何行可能引用同一個表中的「父」行。 (單程做分層數據;還有許多其他的方式。)

但是,當我有這個在我的變更,我得到很多的錯誤運行mix ecto.migrate時:

create_if_not_exists table(:perms, prefix: :accts) do 
    add :title, :string, size: 64, null: false 
    add :description, :text 
    add :parent_id, :integer, references(:perms) 
end 

錯誤消息(UndefinedFunctionError) undefined function Ecto.Migration.Reference.fetch/2 (Ecto.Migration.Reference does not implement the Access behaviour)開始GenServer終止之前。 (這發生在ecto 1.1.5和2.0.0-beta2下。)

回答

4

答案是一個簡單的錯誤:試圖指定外鍵列的列類型會導致錯誤。正確的語法是(注意丟失的:integer原子):

create_if_not_exists table(:perms, prefix: :accts) do 
    add :title, :string, size: 64, null: false 
    add :description, :text 
    add :parent_id, references(:perms) 
end