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