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

时间:2017-12-06 23:49:31

标签: ruby-on-rails postgresql activerecord

我需要将postgres中的id数组从整数更改为uuids。它位于Rails应用程序中,还有其他部分,但我无法弄明白。

我可以在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

我希望这可行,但它告诉我模板上不存在列uuids

1 个答案:

答案 0 :(得分:1)

运行:

Template.reset_column_information

创建列之后,数据迁移之前应刷新缓存并发现新列。 对于同时执行列操作和数据迁移的任何单个迁移文件,这都是相同的。

另一种方法是将其拆分为2-3次迁移。像这样:

  1. 创建列
  2. 数据迁移
  3. 列删除&重命名
  4. 第二种方法的另一个好处是,如果您的数据迁移因任何原因而失败,则您不会处于已创建第一列的伪状态。此状态意味着尝试重新运行迁移将失败,因为该列已存在。

相关问题