这是基于一些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上再现这种行为。
如果我这么做..。
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”
发布于 2022-01-29 23:25:43
PostgreSQL (Rails 7+)中的自定义枚举类型
Rails 7在PostgreSQL中添加了对自定义枚举类型的支持。
因此,现在可以编写如下迁移:
# 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中显示。
源
https://stackoverflow.com/questions/64668994
复制相似问题