Skip to content

Instantly share code, notes, and snippets.

@craigweston
Last active March 8, 2022 14:01
Show Gist options
  • Save craigweston/6e64f6677b281a3d7534fb8d30152341 to your computer and use it in GitHub Desktop.
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.
# 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
@yesthesoup
Copy link

Found this useful, thanks.

With Rails 5.1, I get this error on the migrations_path call:

NoMethodError: undefined method `migrations_path' for ActiveRecord::Migrator:Class

So I replaced it with

Rails.application.paths["db/migrate"].to_a

from https://api.rubyonrails.org/classes/ActiveRecord/Tasks/DatabaseTasks.html#method-i-migrations_paths
as well as the calls in the .run params.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment