将自定义数据类型添加到迁移和架构
下面的示例将一个枚举类型添加到 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 添加到项目并在视图和模型中使用枚举类型。