Rails 7.1 extends enum support for Postgres adapter

Previously rails 7.1 added the support to add enums and drop the enums.

Now, Rails 7.1 has extended the ability to rename an enum, add enum value and rename enum value for the Postgres database adapter.

Before:

Before this change the only way to achieve renaming enum, adding enum value or renaming enum values was to use raw SQL statements.

Renaming the enum:

def up
  execute <<-SQL
    ALTER TYPE user_status RENAME TO user_state;
  SQL
end

Adding a new enum value:

def up
  execute <<-SQL
    ALTER TYPE user_state ADD VALUE 'archived';
    ALTER TYPE user_state ADD VALUE 'pending' BEFORE 'active';
    ALTER TYPE user_state ADD VALUE 'trashed' AFTER  'archived';
  SQL
end

Renaming the enum value:

def up
  execute <<-SQL
    ALTER TYPE user_state RENAME VALUE "trashed" TO "deleted"
  SQL
end

After:

After this change now it is easier to rename the enum, add a new value and rename the enum value

Renaming the enum:

def up
  rename_enum :user_status, to: :user_state
end
--
-- Name: user_state; Type: TYPE; Schema: public; Owner: -
--

CREATE TYPE public.user_state AS ENUM (
    'active'
);

Adding a new enum value:

def up
  add_enum_value :user_state, 'archived'
  add_enum_value :user_state, 'pending', before: 'active'
  add_enum_value :user_state, 'trashed', after: 'archived'
end
CREATE TYPE public.user_state AS ENUM (
    'pending',
    'active',
    'archived',
    'trashed'
);

Renaming the enum value:

Record before:

#<User:0x000000010cb1d390
  id: 1,
  email: "[email protected]",
  phone: "234567890",
  state: "trashed"
>
def up
  rename_enum_value :user_state, from: "trashed", to: "deleted"
end
CREATE TYPE public.user_state AS ENUM (
    'pending',
    'active',
    'archived',
    'deleted'
);

Record after:

#<User:0x000000010cb1d390
  id: 1,
  email: "[email protected]",
  phone: "234567890",
  state: "deleted"
>

References:

Enum in PostgreSQL - https://www.postgresql.org/docs/current/datatype-enum.html

Need help on your Ruby on Rails or React project?

Join Our Newsletter