Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieldiekmeier/edf06931133ac07f630ef2e104df306a to your computer and use it in GitHub Desktop.
Save danieldiekmeier/edf06931133ac07f630ef2e104df306a to your computer and use it in GitHub Desktop.

You probably want the activerecord-postgres_enum gem, because it adds some good stuff for your migrations and allows you to keep using the schema.rb (instead of switching to a schema.sql:

gem 'activerecord-postgres_enum'

Your migration would then look like this:

class AddCountryToCities < ActiveRecord::Migration[5.2]
  def up
    create_enum :city_country, %w(de at ch dk nl)

    change_table :cities do |t|
      t.enum :country, enum_name: :city_country, default: 'de', null: false
    end

    add_index :cities, :country
  end

  def down
    remove_column :cities, :country
    drop_enum :city_country
  end
end

Sadly, you'll also have to manage the enum values in your Model. If you add new values to the Postgres enum, you'll also have to add them here, etc.

# app/models/city.rb

# Use a constant here so we can reuse it in other places in the app!
COUNTRIES = {
  de: 'de',
  at: 'at',
  ch: 'ch',
  dk: 'dk',
  nl: 'nl'
}

enum country: COUNTRIES

As a bonus, you can add translations for your enums to rails admin like so:

# app/models/rails_admin_config/city.rb

module RailsAdminConfig
  module City
    extend ActiveSupport::Concern

    included do
      # This method has to return an array of two-element arrays.
      def country_enum
        ::City::COUNTRIES.values.map { |country_code|
          [I18n.t("location.country.#{country_code}"), country_code]
        }
      end

      rails_admin do
        list do
          field :id
          field :country, :enum
        end
      end
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment