简体   繁体   English

如何在Rails中迁移Postgres数组数据

[英]How to migrate Postgres array data in Rails

I need to change an array of ids in postgres from being integers to being uuids. 我需要将postgres中的id数组从整数更改为uuid。 It's in a Rails app, and there are other parts to this, but I can't figure this out. 它在Rails应用程序中,还有其他部分,但是我无法弄清楚。

I could do it in ActiveRecord, but I can't figure out how to get the sql to do this. 我可以在ActiveRecord中执行此操作,但是我不知道如何获取sql来执行此操作。

add_column :templates, :uuids, :uuid, array: true
Template.find_each do |template|
  new_ids = template.conversations.map do |conversation_id|
    conversation = Conversation.find_by(id: conversation_id)
    conversation.uuid
  end
  template.update_column(:uuids, new_ids)
end
remove_column :templates, :conversations
rename_column :templates, :uuids, :conversations

I would expect this to work, but it tells me that no column uuids exists on templates. 我希望它能起作用,但是它告诉我模板上不存在列uuids

Running: 运行:

Template.reset_column_information

After the column is created and before the data migration should refresh the cache and discover the new column. 在创建列之后且在数据迁移之前,应刷新缓存并发现新列。 This is the same for any single migration file which does both column manipulation and data migrations. 对于任何同时进行列操作和数据迁移的单个迁移文件,这都是相同的。

The alternative is to split this over 2-3 migrations. 另一种方法是将这种迁移分成2-3个迁移。 Like so: 像这样:

  1. Create column 创建列
  2. Data migration 数据迁移
  3. Column remove & rename 列删除和重命名

This second approach has the added benefit that if your data migration fails for any reason you're not left in a pseudo-state where the first column has been created already. 第二种方法的另一个好处是,如果由于任何原因导致数据迁移失败,您将不会处于已经创建第一列的伪状态。 This state means that trying to rerun the migration will fail as the column already exists. 此状态意味着,由于列已存在,尝试重新运行迁移将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM