0

I need to change an array of ids in postgres from being integers to being uuids. It's in a Rails app, and there are other parts to this, but I can't figure this out.

I could do it in ActiveRecord, but I can't figure out how to get the sql to do this.

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.

2
  • what is the column name? is it uuid or uuids? Commented Dec 7, 2017 at 0:06
  • Have you tried adding Template.reset_column_information after the column creation and before the data migration? Commented Dec 7, 2017 at 0:16

1 Answer 1

1

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. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.