首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当将Postgres Enum类型与Rails一起使用时,在迁移中将CREATE类型xyz_setting指定为ENUM会破坏db/schema.rb文件

当将Postgres Enum类型与Rails一起使用时,在迁移中将CREATE类型xyz_setting指定为ENUM会破坏db/schema.rb文件
EN

Stack Overflow用户
提问于 2020-11-03 19:03:51
回答 4查看 2K关注 0票数 2

这是基于一些dev.to文章,这里是https://dev.to/diegocasmo/using-postgres-enum-type-in-rails-30mo,这里是https://dev.to/amplifr/postgres-enums-with-rails-4ld0,还有同一个人的文章,这里是https://medium.com/@diegocasmo/using-postgres-enum-type-in-rails-799db99117ff

如果您遵循上面的建议,建议您通过在Postgres上直接使用CREATE TYPE xyz_setting AS ENUM为Postgres支持的模式创建Rails模式迁移,然后使用它将新字段创建为ENUM ( postgres enum)

不幸的是,这种方法有破坏db/schema.rb文件的缺点。

我认为问题在于Rails核心不支持本地Postgres类型。

我可以在Rails 5.17、5.2.2.4和6.0.3上再现这种行为。

如果我这么做..。

代码语言:javascript
运行
复制
class AddXyzToUsers < ActiveRecord::Migration[5.2]
  def up
    execute <<-DDL
          CREATE TYPE xyz_setting AS ENUM (
            'apple', 'bananna', 'cherry'
          );
    DDL
    add_column :users, :xyz, :xyz_setting
  end

  def down
    remove_column  :users, :xyz
    execute "DROP type xyz_setting;"
  end
end

然后我的模式文件被搞乱了,具体来说,模式用户表没有得到输出的内容,取而代之的是下面的消息

由于遵循StandardError,无法转储表“用户”

列“xyz”的未知类型“xyz_setting”

EN

Stack Overflow用户

回答已采纳

发布于 2022-01-29 23:25:43

PostgreSQL (Rails 7+)中的自定义枚举类型

Rails 7在PostgreSQL中添加了对自定义枚举类型的支持

因此,现在可以编写如下迁移:

代码语言:javascript
运行
复制
# 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

还值得一提的是,当您使用create_enum时,枚举定义和枚举列将在schema.rb中显示。

票数 6
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64668994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档