Ruby on Rails: How can I revert a migration with rake db:migrate?

廉价感情. 提交于 2019-11-29 19:04:23

Run the following command

rake db:migrate:down VERSION=<version>

where <version> is the version number of your migration file you want to revert.

eg. if you want to revert a migration with file name 3846656238_create_users.rb

rake db:migrate:down VERSION=3846656238

Just run this command:

rake db:rollback

I believe there are three options available for reverting migrations (they also overlap):

  1. Roll down the most recent migration:

    rake db:migrate:down # Rails 2 only.

  2. Roll down a number(n) of recent migrations:

    rake db:rollback STEP=n

  3. Roll down to a previous, specific version:

    $ rake db:migrate:down VERSION=nnn # Rails 3 (provide version number also).

Version Number means the SHA(Secure Hash Algorithm) for the commit which is a long hexadecimal number which looks something like 886af3194768917c78e... You can see it by doing git log

You can see these commands (and others) with their descriptions by using rake -T db: which for rails 3.2 includes:

rake db:migrate         # Migrate the database (options: VERSION=x, VERBOSE=false)
rake db:migrate:status  # Display status of migrations
rake db:rollback        # Rolls the schema back to the previous version (specify steps w/ STEP=n)

You can do rollback and specify how many last migrations will be rollbacked, e.g.

rake db:rollback STEP=3

for 3 last migrations.

rake db:migrate:redo

It will undo and reapply the last migration.

LukeBickleTWA

As an new programmer (or to other new programmers)

rake db:rollback works about half the time. I start there.

If not, rake db:migrate:down VERSION=3846656238

plug in VERSION for the version number of your migration file you want to revert.

For rails 5 we can use rails command instead of rake

rails db:migrate:down VERSION=<version>

example

rails db:migrate:down VERSION=20170330090327

Arun JP

Run this command in your terminal:

rake db:migrate:status

or

bundle exec rake db:migrate:status

It shows the status, migration ID's, migration name for all migration we ran previously. select your migration id (i.e your version number) and put that id in the following command after version= ,,, and press enter

bundle exec rake db:migrate:down VERSION=

How to Roll back a migration

(1) First Identify The Migration ID

rake db:migrate:status

  • Copy the ID number.

(2) Then Roll back the migration

rake db:migrate:down VERSION=20190802023239

  • Paste the relevant ID number above. Of course, in your case, the migration ID will be different! Use the correct migration ID.

.......and now you're off to the races!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!