【问题标题】:schema.rb crashes for enum type in postgrespostgres 中枚举类型的 schema.rb 崩溃
【发布时间】:2025-12-02 22:30:01
【问题描述】:

我将user 表的gender 字段用作enum 类型。

迁移也成功运行。但是 schema.rb 会崩溃。

运行迁移后,我的schema.rb 看起来:

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

我的迁移是:

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

我不明白为什么 schema.rb 会崩溃。

【问题讨论】:

  • Unknown type 'gender' for column 'gender'
  • 你最好不要创建一个类型,而是将它们存储为一个整数,然后在你的模型类中添加一个enum gender: { male: 0, female: 1, not_sure: 2, prefer_not_to_disclose: 3 } 行。这将为您提供您期望从数据库获得的应用层的所有功能。顺便说一句according to the guides 声明枚举性别类型的好处为零。它们存储为普通文本列。 btw this might be useful

标签: ruby-on-rails postgresql enums


【解决方案1】:

“Ruby 风格”架构不支持 Postgres 自定义类型。为了使用此功能,您需要切换到 SQL 格式的架构。将config/application.rbconfig.active_record.schema_format的值切换为:sql

【讨论】:

  • 我正在使用 rails 5.2 并在 config/application.rb 中添加行 config.active_record.schema_format = :sql 之后。问题依然存在。我也做了rails db:reset
  • @SourabhBanka 你现在有一个名为db/structure.sql 的文件吗?从现在开始,您的架构应该存储在那里。如果你确实看到了,你可以安全地删除 schema.rb,它不再被 Rails 使用。