With PostgreSQL, we can do something like this:
CREATE TYPE order_status AS ENUM ('placed','shipping','delivered')
From Ecto's official doc, there is no native type to map the Postgres' enumerated type. This module provides a custom type for enumerated structures, but it maps to an integer in the database. I could easily use that library, but I would prefer using the native enumerated type that ships with the database.
Ecto provides also a way to create custom types, but as far as I can see, the custom type must map to a native Ecto type...
Anyone knows if this can be done in a schema with Ecto? If yes, how would the migration work?
Maybe I did something wrong but I just created the type and field like this:
# creating the database 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
and then just made the field a string:
field :post_status, :string
and it seems to work.
Small enhancement for @JustMichael. If you need to rollback, you can use:
def down do
drop table(:posts)
execute("drop type post_type")
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With