DEV Community

Postgres enums with Rails

Dmitry Salahutdinov 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 mai...
Collapse
 
antico5 profile image
Armando Andini

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.

Collapse
 
johand profile image
Johan

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
Collapse
 
dsalahutdinov profile image
Dmitry Salahutdinov

@johand , thanks, fixed

Collapse
 
jasonfb profile image
Jason Fleetwood-Boldt • Edited

unfortunately the db/schema.rb file is messed up with this approach

Could not dump table "users" because of following StandardError

Unknown type 'xyz_setting' for column 'xyz'

stackoverflow.com/questions/646689...

Collapse
 
dsalahutdinov profile image
Dmitry Salahutdinov

Hi! Good point. To have the "native" schema.rb support of postgres enum you could use this ruby gem github.com/bibendi/activerecord-po...

Collapse
 
igor_alexandrov profile image
Igor Alexandrov
Collapse
 
dsalahutdinov profile image
Dmitry Salahutdinov • Edited

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

Collapse
 
yurko profile image
Yurko Bregey • Edited

thanx for sharing! should be remove_column instead of drop_column in migration.

Collapse
 
ortonomy profile image
🅖🅡🅔🅖🅞🅡🅨 🅞🅡🅣🅞🅝

Thanks for the article. I was already looking to Postgres Enums for a solution to my data validation and now you've given me the path to my proposed solution. Happy days.