'schema.rb crashes for enum type in postgres
I am using gender field of my user table as enum type.
Migration also runs sucessfully. But the schema.rb get crashes.
After running the migration, my schema.rb looks:
ActiveRecord::Schema.define(version: 2018_07_23_115046) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
# Could not dump table "users" because of following StandardError
# Unknown type 'gender' for column 'gender'
end
my migration is:
class AddGenderToUsers < ActiveRecord::Migration[5.2]
def up
execute <<-SQL
CREATE TYPE gender AS ENUM ('male', 'female', 'not_sure', 'prefer_not_to_disclose');
SQL
add_column :users, :gender, :gender, index: true
end
def down
remove_column :users, :gender
execute <<-SQL
DROP TYPE gender;
SQL
end
end
I don't understand why the schema.rb crashes.
Solution 1:[1]
Custom enum types in PostgreSQL (Rails 7+)
schema.rb is crashing since Rails had no built-in support for custom enum types in PostgreSQL.
Starting from Rails 7, a new create_enum method is introduced that allows to write migrations like so:
# db/migrate/20131220144913_create_articles.rb
def up
create_enum :article_status, ["draft", "published"]
create_table :articles do |t|
t.enum :status, enum_type: :article_status, default: "draft", null: false
end
end
# There's no built in support for dropping enums, but you can do it manually.
# You should first drop any table that depends on them.
def down
drop_table :articles
execute <<-SQL
DROP TYPE article_status;
SQL
end
This way schema.rb will be updated automatically and there is no need to change config.active_record.schema_format to sql (at least for this particular case).
Sources:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marian13 |
