Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Postgres' enumerated type with Ecto

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?

like image 865
Jean-Pierre Bécotte Avatar asked Feb 06 '16 20:02

Jean-Pierre Bécotte


2 Answers

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.

like image 187
NoDisplayName Avatar answered Sep 18 '22 12:09

NoDisplayName


Small enhancement for @JustMichael. If you need to rollback, you can use:

def down do
  drop table(:posts)
  execute("drop type post_type")
end
like image 20
swennemen Avatar answered Sep 21 '22 12:09

swennemen