Skip to content
Carlos edited this page Apr 12, 2017 · 16 revisions

Enum type manager. It creates a separated class to hold each enum set that can be used by multiple models, it also keeps the database data consistent. The enum type is known to have a better performance against string- and integer-like enums. PostgreSQL Docs

How it works

Migration

First you have to create the enum during your migration, since it's the database that holds the list of possible values.

create_enum :status, %i(created draft published archived)

Some other examples are:

# ['status_foo', 'status_bar']
create_enum :status, %i(foo bar), prefix: true
# 'foo_tst', 'bar_tst']
create_enum :status, %i(foo bar), suffix: 'tst'

You can also manage this type along other migrations, renaming, adding values, or deleting it.

# Rename enum by renaming the type it represents
rename_type :status, :content_status

# Adding values
add_enum_values :status, %i(baz qux)                      # To the end of the list
add_enum_values :status, %i(baz qux), prepend: true       # At the beginning of the list
add_enum_values :status, %i(baz qux), after: 'foo'        # After a certain value
add_enum_values :status, %i(baz qux), before: 'foo'       # Before a certain value
add_enum_values :status, %i(baz qux), prefix: true        # With type name as prefix
add_enum_values :status, %i(baz qux), suffix: 'tst'       # With a specific suffix

# Deleting an enum by dropping the type it represents
drop_type :status
Clone this wiki locally