如何在Rails迁移中添加PostgreSQL的OID数据类型
在Rails 6.1迁移中添加PostgreSQL OID类型列的最佳实践
针对PostgreSQL 12,Rails没有提供OID类型的直接映射,你可以通过以下两种方式实现:
1. 直接在迁移中使用原生数据库类型
这是最简单直接的方式,利用t.column方法绕过Rails的通用类型映射,直接指定PostgreSQL的oid原生类型:
class MigrationName < ActiveRecord::Migration[6.1] def up # 原有表创建代码... # 新增包含OID列的表 create_table :my_table_3, if_not_exists: true do |t| # 直接指定原生类型为oid t.column :ref_oid, 'oid', null: false, annotations: { is_pi: false } t.string :description, annotations: { is_pi: false } # 其他列... end end def down # 原有表删除代码... drop_table :my_table_3, if_exists: true end end
2. 自定义ActiveRecord类型(可选,用于模型层规范处理)
如果需要在模型中更优雅地处理OID类型(确保参数绑定、类型转换的正确性),可以自定义一个ActiveRecord类型:
- 创建初始化文件
config/initializers/active_record_oid_type.rb:
class OIDType < ActiveRecord::Type::Integer def sql_type 'oid' end end ActiveRecord::Type.register(:oid, OIDType)
- 在迁移中直接使用自定义的
:oid类型:
create_table :my_table_3, if_not_exists: true do |t| t.oid :ref_oid, null: false, annotations: { is_pi: false } # 其他列... end
- 在对应模型中声明属性类型:
class MyTable3 < ApplicationRecord attribute :ref_oid, :oid end
这种方式让模型层的类型处理更符合Rails规范,同时保留PostgreSQL OID类型的特性。
内容的提问来源于stack exchange,提问作者Em Ae
相关产品推荐
相关产品推荐

