Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run migrations from rails console

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

It sucks to wait for the rails environment to load!

like image 572
rafamvc Avatar asked Sep 02 '11 17:09

rafamvc


People also ask

How do I run a migration in Rails?

Rails Migration allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code. Teams of developers − If one person makes a schema change, the other developers just need to update, and run "rake migrate".

How do rails track migrations?

Every time a migration is generated using the rails g migration command, Rails generates the migration file with a unique timestamp. The timestamp is in the format YYYYMMDDHHMMSS . Whenever a migration is run, Rails inserts the migration timestamp into an internal table schema_migrations .

How do I run migration in node JS?

Creating Migrations To create a migration, execute db-migrate create with a title. node-db-migrate will create a node module within ./migrations/ which contains the following two exports: exports. up = function (db, callback) { callback(); }; exports.

Are Rails migrations run in a transaction?

On databases that support transactions with statements that change the schema, migrations are wrapped in a transaction. If the database does not support this then when a migration fails the parts of it that succeeded will not be rolled back. You will have to rollback the changes that were made by hand.


2 Answers

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

like image 97
Homan Avatar answered Sep 28 '22 02:09

Homan


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 1 ActiveRecord::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 1 ActiveRecord::MigrationContext.new("db/migrate").rollback 3 
like image 34
Benoit Garret Avatar answered Sep 28 '22 01:09

Benoit Garret