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'
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
Written by Ryan MacGillivray
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#