Skip to content

Instantly share code, notes, and snippets.

@astuyve
Created June 26, 2018 19:33
Show Gist options
  • Save astuyve/09c699eb08b687c4e0b8e0541a879e9b to your computer and use it in GitHub Desktop.
Save astuyve/09c699eb08b687c4e0b8e0541a879e9b to your computer and use it in GitHub Desktop.
Custom database migrations in Rails 5+
# Rails has long supported database migrations to help you evolve your database schema over time.
# However, mature Rails applications often need migration-like tasks which may not alter the schema, or may have special considerations.
# Specifically, I've had to implement an after-deploy migration pattern, and a late night migration pattern.
# After-deploys are used for non-schema changes. If I have a bunch of corrupt data to clean up, or a 1-time import to process,
# which doesn't really demand its own rake task.
# Late-night migrations might be schema changes that can lock a table or cause other issues that would arise during the day.
# Rails 5 introduced multi-database support, which also often benefits from multiple directories for migrations. You can leverage
# that logic and create a new task for special migrations like this
namespace :db do
desc "Migrate the database through scripts in db/migrate_after_deploy. Target specific version with VERSION=x. Turn off output with VERBOSE=false."
task :migrate_after_deploy => :environment do
ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
ActiveRecord::MigrationContext.new('db/migrate_after_deploy').migrate(ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
end
end
# Read more about this change here: https://github.com/rails/rails/commit/a2827ec9811b5012e8e366011fd44c8eb53fc714
# Thanks to @eileencodes for the excellent commit message :) https://github.com/eileencodes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment