Rails 更改主键/外键数据类型

问题描述

我的 rails 应用从第三方服务导入了一堆资源,这是应用的真实来源。 API 使用 json 资源及其 ID 进行响应,例如:

 {"_id"=>"604d3d6ed64d52b8bfe84b","name"=>"Advanced Stock Trading Course + Strategies","author"=>"davd@fullsts.com",}

我的应用程序导入这些资源并将它们复制到 postgres 数据库中它们自己的表中。看起来像:

  create_table "programs",force: :cascade do |t|
    t.jsonb "lms_data",default: "{}",null: false
    t.bigint "author_id"
    t.jsonb "default_lms_image",null: false
    t.index ["account_id"],name: "index_programs_on_account_id"
    t.index ["author_id"],name: "index_programs_on_author_id"
    t.index ["lms_data"],name: "index_programs_on_lms_data",using: :gin
  end

其中 lms_data 存储来自第三方 API 的原始 json。

最初,我在自动增量模式下使用经典的 Bigint ID 主键创建了此表。由于第三方服务是我唯一的真实来源。我实际上希望他们的 id 成为我的主键“_id”=>“604d3d6ed64d52b8bfe84b”,即字符串“604d3d6ed64d52b8bfe84b”。

但是,我有其他表已经将 program_id 引用为外键,例如当我尝试运行此迁移时:

  def change
    change_column :sessions,:program_id,:string
    change_column :tickets,:string
    change_column :programs,:id,:string
  end

  def down
    change_column :sessions,:bigint
    change_column :tickets,:bigint
    change_column :programs,:bigint
  end

我收到此错误

Caused by:
ActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR:  foreign key constraint "fk_rails_35ef875d99" cannot be implemented
DETAIL:  Key columns "program_id" and "id" are of incompatible types: character varying and bigint.

在这种情况下,有没有办法迁移我的主键和外键?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)