Starting migration from rails console

Is there a way to run rake commands for db: migrate and db: rollback on the console?

It sucks, waiting for the rail environment to load!

+53
ruby-on-rails
Sep 02 2018-11-17T00:
source share
7 answers

This will allow you to migrate without rebooting the entire rail environment:

ActiveRecord::Migrator.migrate "db/migrate" 

and rollback:

 # 3 is the number of migration to rollback, optional, defaults to 1 ActiveRecord::Migrator.rollback "db/migrate", 3 
+66
Sep 02 2018-11-17T00:
source share

In the console:

 ActiveRecord::Migration.remove_column :table_name, :column_name 

To update the schema.rb file after starting the migration from the console, you must run rails db:migrate

+71
May 10 '14 at 18:49
source share

Another way I found to just run some migration command from the console is as follows:

 ActiveRecord::Schema.define do create_table :foo do |t| t.string :bar t.timestamps end end 

This has the advantage that the content inside the block is only compatible with copying and pasting random content from the actual migration file / schema.rb .

+20
Mar 18 '15 at 3:15
source share

For rails 5.2, the accepted answer has been deleted and replaced with

 ActiveRecord::MigrationContext.new("db/migrate").migrate 

Remember that this may change for future versions of rails, as they work to add multiple database connections.

+4
Oct 10 '18 at 11:18
source share

I needed to pretend that the migration was started in order to unlock the deployment, this can be done with:

 class Mig < ActiveRecord::Base; self.table_name = 'schema_migrations';end Mig.create! version: '20180611172637' 
+2
Jun 18 '18 at 21:25
source share

You can use% x [command]

 %x[rake db:migrate] 
0
Sep 02 '11 at 17:50
source share

I created a method in my .irbrc file that starts the migration, then reboots the console:

 def migrate if defined? Rails::Console # turn off info logging for Rails 3 old_log_level = ActiveRecord::Base.logger.try(:sev_threshold) ActiveRecord::Base.logger.sev_threshold = Logger::WARN end reload! && migations_ran = true if ActiveRecord::Migrator.migrate(Rails.root.join("db/migrate")).any? ActiveRecord::Base.logger.sev_threshold = old_log_level if defined? old_log_level migations_ran ||= nil # useful exit status end 

See the whole file here: https://gist.github.com/imme5150/6548368

0
Sep 13 '13 at 9:17
source share



All Articles