Rails Enums and PostgreSQL Enums
Today I learned that Rails Enum works pretty well with PostgreSQL Enum.
Enum in PostgreSQL work as a new type with restricted values and if you need to guarantee data integrity there's no best way to do that than in your database. Here is how we create a new enum in PostgreSQL and use in a new column:
class AddEnumToTrafficLights < ActiveRecord::Migration
  def up
    ActiveRecord::Base.connection.execute <<~SQL
      CREATE TYPE color AS ENUM ('red', 'green', 'blue');
    SQL
    add_column :traffic_lights, :color, :color, index: true
  end
  def down
    remove_column :traffic_lights, :color
    ActiveRecord::Base.connection.execute <<~SQL
      DROP TYPE color;
    SQL
  end
end
In Rails models I prefer to use Hash syntax when mapping Ruby symbols to database values.
class TrafficLight < ApplicationRecord
  enum color: {
    red: 'red',
    green: 'green',
    blue: 'blue',
  }
end
And now Enum in action:
TrafficLight.colors
#=> {
#=>   "red"=>"red",
#=>   "green"=>"green",
#=>   "blue"=>"blue"
#=> }
TrafficLight.last.blue!
TrafficLight.last.color
#=> "blue"
h/t @ joshuadavey
Tweet