Last Updated: February 25, 2016
· ryanmacg

Rake migration to convert integer to array in postgres

If you find yourself in the unenviable position of having to convert a series of already existing integers into arrays in a rails application you can use the below. There is a reversible method you can do using raw sql and min but I think that might be a step too far.

class ChangeXIdColumn < ActiveRecord::Migration
  def up
    remove_index :table_name, :x_id
    change_column :table_name, :x_id, 'text[] USING ARRAY[x_id]::INTEGER[]', array: true, null: false, default: []
    rename_column :table_name, :x_id, :x_ids
    add_index :table_name, :x_ids, using: 'gin'

  def down
    raise ActiveRecord::IrreversibleMigration