將自定義資料型別新增到遷移和架構
下面的示例將一個列舉型別新增到 postgres 資料庫。
首先,編輯遷移檔案 (使用 mix ecto.gen.migration
建立):
def up do
# creating the enumerated type
execute("CREATE TYPE post_status AS ENUM ('published', 'editing')")
# creating a table with the column
create table(:posts) do
add :post_status, :post_status, null: false
end
end
def down do
drop table(:posts)
execute("DROP TYPE post_status")
end
其次,在模型檔案中新增具有 Elixir 型別的欄位:
schema "posts" do
field :post_status, :string
end
或實施 Ecto.Type
行為。
後者的一個很好的例子是 ecto_enum
包,它可以用作模板。它的用法在其 github 頁面 上有詳細記錄。
此提交顯示了 Phoenix 專案中的示例用法,即將 enum_ecto 新增到專案並在檢視和模型中使用列舉型別。