Run migrations from rails console Run migrations from rails console ruby-on-rails ruby-on-rails

Run migrations from rails console


In the console:

ActiveRecord::Migration.remove_column :table_name, :column_name

To update your schema.rb file after running migrations from the console, you must run rails db:migrate


Rails <= 4

This will allow you to migrate without reloading the whole rails environment:

ActiveRecord::Migrator.migrate "db/migrate"

and rollback:

# 3 is the number of migration to rollback, optional, defaults to 1ActiveRecord::Migrator.rollback "db/migrate", 3

Rails >= 5 (thanks to @gssbzn, his answer is below)

Migrate :

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

And rollback :

# 3 is the number of migration to rollback, optional, defaults to 1ActiveRecord::MigrationContext.new("db/migrate").rollback 3


Another way that I find neater to just run some migration command from console is this:

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

This has the advantage that the contents inside the block is compatible with just copy and pasting random contents from a real migration file / schema.rb.