The example below adds an enumerated type to a postgres database.
First, edit the migration file (created with 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
Second, in the model file either add a field with an Elixir type :
schema "posts" do
field :post_status, :string
end
or implement the Ecto.Type
behaviour.
A good example for the latter is the ecto_enum
package and it can be used as a template. Its usage is well documented on its github page.
This commit shows an example usage in a Phoenix project from adding enum_ecto to the project and using the enumerated type in views and models.