Jas*_* FB 2 postgresql enums ruby-on-rails
这是基于这里的一些 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
如果您遵循上述建议,建议您CREATE TYPE xyz_setting AS ENUM直接在 Postgres 上使用,为您的 Postgres 支持的架构创建 Rails 架构迁移,然后使用它来创建新字段作为 ENUM(postgres 枚举)
不幸的是,这种方法的缺点是会破坏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
Run Code Online (Sandbox Code Playgroud)
那么我的模式文件就混乱了,具体来说,模式用户表没有得到任何输出,取而代之的是这条消息
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
Run Code Online (Sandbox Code Playgroud)
还值得一提的是,当您使用 时create_enum,枚举定义和枚举列将显示在 中schema.rb。
资料来源:
| 归档时间: |
|
| 查看次数: |
3720 次 |
| 最近记录: |