Skip to content

Instantly share code, notes, and snippets.

@aaronsama
Last active January 24, 2018 10:04
Show Gist options
  • Save aaronsama/932667e64fb5f4bbec6c58696451a699 to your computer and use it in GitHub Desktop.
Save aaronsama/932667e64fb5f4bbec6c58696451a699 to your computer and use it in GitHub Desktop.
Migrates all your IDs to bigint. Useful when migrating from Rails < 5.1 to Rails 5.1+
class AllToBigint < ActiveRecord::Migration[5.1]
def up
switch_all_to(__method__, :bigint)
end
def down
switch_all_to(__method__, :integer)
end
private
def switch_all_to(direction, new_type)
remove_and_restore_fk direction: direction do
# force require all models
Rails.application.eager_load!
index_by_table_name = ActiveRecord::Base.descendants.reject { |klass| klass.abstract_class || (klass.name.deconstantize == "MenuCir") }.index_by(&:table_name)
index_by_table_name.each do |table_name, model|
next if %w[schema_migrations ar_internal_metadata].include? table_name
change_column table_name.to_sym, :id, new_type, auto_increment: true unless model.name.start_with?('HABTM')
model.reflect_on_all_associations(:belongs_to).each do |association|
if association.name == :left_side
change_column table_name.to_sym, :"#{association.klass.name.demodulize.underscore}_id", new_type
else
change_column table_name.to_sym, :"#{association.name}_id", new_type
end
end
end
# friendly_id_slugs (if you use FriendlyID)
change_column :friendly_id_slugs, :id, new_type, auto_increment: true
change_column :friendly_id_slugs, :sluggable_id, new_type
end
end
def remove_and_restore_fk(direction:)
# Remove all FK to avoid having to deal with dependencies
# remove all your foreign keys (manually)
# omissis - I had to copy them from schema.rb. This is needed to avoid FK errors
yield
# omissis
# add them again (manually)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment