Reputation: 1117
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.
Upvotes: 8
Views: 2201
Reputation: 9308
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:
Upvotes: 0
Reputation: 14851
Postgres custom types aren't supported by "Ruby-style" schemas. In order to use this functionality, you'll need to switch to a SQL-formatted schema. Switch the value of config.active_record.schema_format
in config/application.rb
to :sql
.
Upvotes: 14