Rails migration: best way to retrieve current migration version

Ruby on-RailsRuby on-Rails-3

Ruby on-Rails Problem Overview


Is there good way to retrieve migration version number?

I need to implement a method in a model which behave differently on and beyond a specific migration version.

I found assume_migrated_upto_version in connection adapter is retrieving version from database but can't find others.


Background: I'm trying to remove two columns from table A, want to move them into table B, and add association to the table B from the table A.

During this change, I need to access these two columns. but after that, I want to add proxy method for these columns for compatibility.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

There's a much nicer way: rake db:migrate:status

up     20120530222941  Create shenanigans
up     20120613030015  *** NO FILE ***

Indicating that I've deleted my latest migration file.

Or more simply:

> rake db:version
Current version: 20120613030015

Solution 2 - Ruby on-Rails

Rails 5.2 and higher:

> ApplicationRecord.connection.migration_context.current_version
   (0.3ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
=> 20200510093804

> ApplicationRecord.connection.migration_context.get_all_versions
   (0.3ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
=> [20191005164928,
    20191006111502,
   ...

 
Rails up to 5.1.7:

> ActiveRecord::Migrator.current_version
   (0.2ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" 
=> 20120110085802

> ActiveRecord::Migrator.get_all_versions
   (0.3ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" 
=> [20111114121610,
    20111115091108,
   ...

Solution 3 - Ruby on-Rails

For Rails 5.x/6.x:

puts ApplicationRecord.connection.migration_context.current_version
puts ApplicationRecord.connection.migration_context.get_all_versions

Solution 4 - Ruby on-Rails

If you don't want to do this without loading your app you can create a script like this:

#!/usr/bin/env ruby

root = File.expand_path("../..", __FILE__)
lines = `ls #{root}/db/migrate`
puts lines.split("\n").last.split(" ").last.split("_").first

Note the root line is because my script is in a bin dir

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionshigeyaView Question on Stackoverflow
Solution 1 - Ruby on-RailsPeter EhrlichView Answer on Stackoverflow
Solution 2 - Ruby on-RailsjibielView Answer on Stackoverflow
Solution 3 - Ruby on-RailsShai ColemanView Answer on Stackoverflow
Solution 4 - Ruby on-RailsTonyView Answer on Stackoverflow