Using enum columns in Ecto and Phoenix

I’ve been reading the source code to Level and saw this migration:

defmodule Level.Repo.Migrations.CreateSpaceUsers do
  use Ecto.Migration

  def up do
    execute("CREATE TYPE space_user_role AS ENUM ('OWNER','ADMIN','MEMBER')")
    execute("CREATE TYPE space_user_state AS ENUM ('ACTIVE','DISABLED')")

    create table(:space_users, primary_key: false) do
      # ...
      add :state, :space_user_state, null: false, default: "ACTIVE"
      add :role, :space_user_role, null: false, default: "MEMBER"

      timestamps()
    end
  end

  def down do
    drop table(:space_users)
    execute("DROP TYPE space_user_role")
    execute("DROP TYPE space_user_state")
  end
end

I don’t understand this line

add :role, :space_user_role, null: false, default: "MEMBER"

Specifically the passing of :space_user_role as the 2nd argument. I know that table is created at the beginning of up but don’t understand what passing a table name to add accomplishes. I looked at the docs but couldn’t find anything related to this. Can anyone explain what is going on here?

2 Likes

It looks like the 2nd argument is the field type which matches the Enum type created earlier in the migration.

2 Likes

Ah my eyes were playing tricks on me. I could have sworn that line was creating a roles table.

I’m coming from Rails and I’ve never seen this done before. I’ll read up a bit more on creating database types.

Thanks for your help!

1 Like