Postgres enums with Rails

Salahutdinov Dmitry on July 11, 2018

Introduction Enum - is a user-defined data type representing a set of named values. In general, the idea of enums aims to provide 2 m... [Read Full]
markdown guide
 

Everything is great until we will need to add value to your enumeration

You can define your enums as a hash to make the mapping explicit, then AR will not remap your values when you add something.

 

Also if storage size is an issue then you can add the limit: option to the migration, which let's you select integer sizes:

gist.github.com/stream7/1069589/e0...

So in your example something like:

t.integer :status, null: false, limit: 1

On MySQL this will become a tinyint (1 byte) and on Postgres a smallint (2 bytes). Of course this doesn't solve the problem of enum values not being meaningful outside the app context.

 

Michael, thanks for your comment!
This is great idea, which comes after the fail without having explicit values first :)

 

Thanks for sharing this knowledge!

I noticed a mistake on the migration:

              WHEN 0 THEN 'email'::user_notification_channel
              WHEN 0 THEN 'webpush'::user_notification_channel
              WHEN 0 THEN 'facebook'::user_notification_channel

Every value is 0, I think it should be 0, 1 and 2.

 

Nice post @dsalahutdinov , apart from what @antico5 says I see another detail here, is that the last one should be

WHEN 2 THEN 'telegram'::user_notification_channel

instead of

WHEN 2 THEN 'facebook'::user_notification_channel
 
 
code of conduct - report abuse