fireproofsocks
Ecto Schema: Enum Data Type?
Is the only way to support enum columns in an Ecto schema by using a 3rd party package like GitHub - gjaldon/ecto_enum: Ecto extension to support enums in models · GitHub ?
Thanks!
Most Liked
dwahyudi
I used enum in rails before, once upon a time, a co-worker just inserted a value in the middle of the enum array and it destroyed the data. ![]()
halostatue
No. You just specify the enum column as string in the schema.
I can’t tell you exactly what the migration will look like; we have two projects where we use enums pretty heavily. The first project uses Ecto, Ecto migrations, and Ecto.Enum. The second uses Ecto, Sqitch (which uses straight-up SQL), and does not use Ecto.Enum.
Based on our experiences, I would recommend not using Ecto.Enum if you’re using PostgreSQL. There’s nothing explicitly wrong with the library itself (the documentation is a different matter), but it provides exactly two conveniences:
-
The ability to specify enums in queries using atoms instead of binaries (
:activeinstead of"active"). -
The ability to create new enums without knowing the PostgreSQL ‘magic’ (which isn’t really that magic). This really isn’t that hard:
def up do execute ~s""" IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'user_status') THEN CREATE TYPE user_status AS ENUM ('active', 'inactive'); END IF; """ endNote that you have to drop to SQL anyway to add a new value to an enum, and the Ecto.Enum documentation is flat out wrong about the syntax to use (it will cause your migrations to fail if you have to roll back at all, because there’s no possible
downphase toALTER TYPE type ADD VALUE 'value'). Instead of what the Ecto.Enum documentation recommends, useALTER TYPE type ADD VALUE IF NOT EXISTS 'value'(I submitted this change as a PR, but the maintainer rejected this for some reason).
Qqwy
This is the reason you should always specify the numeric values in an enum. (This is true for both Ruby and any other language with numeric enums like any C-like language)









