davidwessman
davidwessman

Reputation: 1228

Run ActiveRecord migrations without Rails

I am trying to update a gem called textacular to be compatible with latest rails version.

In the development Rake-tasks we need to run a few ActiveRecord migrations - without Rails.

Today it looks like:

namespace :migrate do
    desc 'Run the test database migrations'
    task :up => :'db:connect' do
      ActiveRecord::Migrator.up 'db/migrate'
    end

    desc 'Reverse the test database migrations'
    task :down => :'db:connect' do
      ActiveRecord::Migrator.down 'db/migrate'
    end
end

However when using ActiveRecord >= 5, it fails with:

NoMethodError: undefined method 'up' for ActiveRecord::Migrator:Class.

I have tried to look through the source code for ActiveRecord, tried a bunch of different methods but have not managed to run the migrations.

Does anyone have a hint of what to do?

Edit

Using ActiveRecord::Migration.up does nothing, probably just returns based on the method.

Using ActiveRecord::Migration.migrate(:up) gives output:

==  ActiveRecord::Migration: migrating ========================================
==  ActiveRecord::Migration: migrated (0.0000s) ===============================

All migrations are in the folder db/migrate.

Upvotes: 6

Views: 3867

Answers (3)

W4rQCC1yGh
W4rQCC1yGh

Reputation: 2219

By looking at the rails github page then starting from Rails 5.2 the Migrator class is cut down quite a bit. Much of its methods have moved to Migration class instead (including the .up method).

Therefore just replace ActiveRecord::Migrator with ActiveRecord::Migration.

Upvotes: 2

Ruan Carlos
Ruan Carlos

Reputation: 505

You can also use this command:

ActiveRecord::MigrationContext.new(Rails.root.join('db', 'migrate'), ActiveRecord::SchemaMigration).migrate

Upvotes: 7

davidwessman
davidwessman

Reputation: 1228

I managed to solve this (until Rails 6 is release at least), the implementation can be seen on textacular

task :up => :'db:connect' do
  migrations = if ActiveRecord.version.version >= '5.2'
    ActiveRecord::Migration.new.migration_context.migrations
  else
    ActiveRecord::Migrator.migrations('db/migrate')
  end
  ActiveRecord::Migrator.new(:up, migrations, nil).migrate
end

Not very satisfied with this solution, but this was the only way I could get the migrations to run on Rails 5, 5.1 and 5.2.

Upvotes: 2

Related Questions