这是基于一些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中显示。
源
发布于 2020-11-04 08:23:37
发布于 2022-06-05 17:35:18
在Rails 7中,如果您使用的是PostgreSQL,那么现在可以这样做:
rails generate model Post title:string body:text post_type:enum您的迁移可以类似于:
class CreatePosts < ActiveRecord::Migration[7.0]
def change
create_enum :post_option, ["draft", "private", "published"]
create_table :posts do |t|
t.string :title
t.text :body
t.enum :post_type, enum_type: "post_option", default: "draft", null: false
t.timestamps
end
add_index :posts, :post_type
end
end您的模式应该如下所示:
ActiveRecord::Schema[7.0].define(version: 2022_06_04_221707) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
# Custom types defined in this database.
# Note that some types may not work with other database engines. Be careful if changing database.
create_enum "post_option", ["draft", "private", "published"]
create_table "posts", force: :cascade do |t|
t.string "title", default: ""
t.text "body", default: ""
t.enum "post_type", default: "draft", null: false, enum_type: "post_option"
t.string "image", default: ""
t.index ["post_type"], name: "index_posts_on_post_type"
end
end然后,在您的模型中,您可以简单地说:
enum :post_type, draft: "draft", private: "private", published: "published"https://stackoverflow.com/questions/64668994
复制相似问题