Last active
March 8, 2022 14:01
-
-
Save craigweston/6e64f6677b281a3d7534fb8d30152341 to your computer and use it in GitHub Desktop.
Rake db migration touch command. Updates an existing migration version to latest version.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# called with: rake db:migrate:touch['123456_migration_file.rb'] | |
namespace :db do | |
namespace :migrate do | |
desc "Touch migration - Renames file with new version and runs db:migrate:down with old version and db:migrate:up with new version" | |
task :touch, [:filename] => [:environment] do |t, args| | |
migrate_path = ActiveRecord::Migrator.migrations_path | |
filename = args[:filename] | |
next_version = ActiveRecord::Migrator.current_version.to_i + 1 | |
new_filename = filename.gsub(/^\d+/, next_version.to_s) | |
match = filename.match(/(^\d+)/) | |
raise 'Error no version' unless match | |
previous_version = match.captures.first | |
ActiveRecord::Migrator.run(:down, ActiveRecord::Migrator.migrations_path, previous_version.to_i) | |
File.rename(File.join(migrate_path, filename), File.join(migrate_path, new_filename)) | |
ActiveRecord::Migrator.run(:up, ActiveRecord::Migrator.migrations_path, next_version.to_i) | |
puts "Updated migration filename from: #{filename} to: #{new_filename}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found this useful, thanks.
With Rails 5.1, I get this error on the
migrations_path
call:So I replaced it with
from https://api.rubyonrails.org/classes/ActiveRecord/Tasks/DatabaseTasks.html#method-i-migrations_paths
as well as the calls in the
.run
params.