880

I have the following migration file db\migrate\20100905201547_create_blocks.rb

How can I specifically rollback that migration file?

tronerta
  • 73
  • 1
  • 8
AnApprentice
  • 97,752
  • 174
  • 583
  • 971
  • 1
    Does this address the issue? You'll just need to do `Class.down` http://stackoverflow.com/questions/753919/run-a-single-migration-file – danivovich Sep 05 '10 at 20:39
  • 4
    Every information on migrations [Here](http://guides.rubyonrails.org/migrations.html) – Nishutosh Sharma Jan 02 '13 at 06:08
  • 1
    Do you want to roll back only that single specific migration (even if there are newer migrations that come after it)? Or do you want to roll back the database to the state it was in before that migration, and any subsequent migrations, were applied? – Jon Schneider Oct 03 '18 at 20:40

14 Answers14

1489
rake db:rollback STEP=1

Is a way to do this, if the migration you want to rollback is the last one applied. You can substitute 1 for however many migrations you want to go back.

For example:

rake db:rollback STEP=5

Will also rollback all the migration that happened later (4, 3, 2 and also 1).

To roll back all migrations back to (and including) a target migration, use: (This corrected command was added AFTER all the comments pointing out the error in the original post)

rake db:migrate VERSION=20100905201547

In order to rollback ONLY ONE specific migration (OUT OF ORDER) use:

rake db:migrate:down VERSION=20100905201547

Note that this will NOT rollback any interceding migrations -- only the one listed. If that is not what you intended, you can safely run rake db:migrate and it will re-run only that one, skipping any others that were not previously rolled back.

And if you ever want to migrate a single migration out of order, there is also its inverse db:migrate:up:

rake db:migrate:up VERSION=20100905201547
Qqwy
  • 4,675
  • 4
  • 31
  • 68
Zachary Wright
  • 20,532
  • 9
  • 40
  • 48
  • 14
    "In order to rollback to specific version" - doesn't the command that follows only rollback a specific migration, rather than rolling all the way back to that version? – Andrew Grimm Jul 11 '16 at 07:57
  • 12
    "In order to rollback to specific version use..." **This answer is incorrect!** This will rollback the migration in isolation as explained by other answers. – Rhys van der Waerden Nov 22 '16 at 03:44
  • 3
    WARNING: I made this mistake: only use rake db:migrate:down VERSION=20100905201547 to rollback IN ISOLATION!!! one migration file. This is mentioned in the comment above, but I missed it. – pixelearth Jan 26 '17 at 21:25
  • 4
    Another word of warning - don't ever do `STEP=-1`. I did that once and it went mad, rolling back everything. Not nice! This was Rails 4.2 - I guess it may be fixed by now. – Dave Hartnoll Mar 13 '18 at 16:37
  • 1
    Wrote an article in my blog about migrations, that explains how and when to use these commands: https://railsguides.net/polish-rails-migrations/ – ka8725 Apr 14 '18 at 01:22
  • Nice blog but why do you guess the migration's nationality?! :D – Mark Nov 28 '18 at 15:42
  • On rails 5.2 this did not also rollback the target migration for me. As mentioned in 'rake db:migrate VERSION=20100905201547' – Cody Elhard Apr 19 '19 at 13:06
  • 2
    Don't forget you can use `rake db:migrate:status` to see all the specific migrations and their status! – Danodemo Feb 20 '20 at 18:04
898
rake db:migrate:down VERSION=20100905201547

will roll back the specific file.


To find the version of all migrations, you can use this command:

rake db:migrate:status

Or, simply the prefix of the migration's file name is the version you need to rollback.


See the Ruby on Rails guide entry on migrations.

Zia Ul Rehman Mughal
  • 1,755
  • 18
  • 35
John Creamer
  • 9,184
  • 1
  • 11
  • 8
  • 49
    Definitely the preferred answer in my opinion. – streetlogics Feb 27 '13 at 17:07
  • Would this rollback migration be pushed across all remote servers, eg. Heroku? Would it be better to create a new migration file just to undo the specific changes? – cevaris Aug 11 '13 at 00:00
  • 30
    It's worth mentioning that if you roll back a specific migration and do not want it to re-migrate on upcoming rake tasks, then delete the migrate file as well. – BradGreens Aug 20 '13 at 18:17
  • Yup. This is way better than stepping. Stepping has its place, but if you just want to fix a single migration (and don't care about losing the data in the table, obviously) this is the stuff of legends. – Dudo Sep 04 '13 at 17:50
  • 4
    Note: it seems that if the up migration never succeeded but have only been partially executed, the down does nothing. – cyrilchampier Oct 09 '13 at 12:13
  • Even rake db:migrate VERSION=old_version works! – sadfuzzy Feb 14 '14 at 09:54
  • Can I simply remove the migration file once performing this migration down method? – Samuel Mar 09 '14 at 22:39
  • 1
    @nerith, it's probably true only for databases which doesn't support Transactional DDL. MySQL doesn't support Transactional DDL: http://dev.mysql.com/doc/refman/5.0/en/cannot-roll-back.html PostreSQL does: https://wiki.postgresql.org/wiki/Transactional_DDL_in_PostgreSQL:_A_Competitive_Analysis So if your migration on MySQL database is broken then you have manually to delete part of migration that succeeded. – Иван Бишевац Jul 25 '14 at 09:33
  • 1
    Another observation regarding @BradGreens comment. If you do want to remove the migration file, and it has already been deployed, you'll want to roll back production/staging before you commit the code with the removed file. Otherwise you won't be able to rollback/migrate:down. – AdamT Aug 06 '17 at 07:21
  • Note that this does not roll back all migrations up to and including the specified migration; rather, it rolls back just that single specific migration (leaving any subsequent migrations still applied). – Jon Schneider Sep 17 '18 at 18:16
62

To rollback the last migration you can do:

rake db:rollback

If you want to rollback a specific migration with a version you should do:

rake db:migrate:down VERSION=YOUR_MIGRATION_VERSION

For e.g. if the version is 20141201122027, you will do:

rake db:migrate:down VERSION=20141201122027

to rollback that specific migration.

Waleed
  • 686
  • 5
  • 4
35

You can rollback your migration by using rake db:rollback with different options. The syntax will be different according to your requirements.

If you want to rollback just the last migration, then you can use either

rake db:rollback

or

rake db:rollback STEP=1

If you want rollback number of migrations at once, then you simply pass an argument:

rake db:rollback STEP=n

where n is number of migrations to rollback, counting from latest migration.

If you want to rollback to a specific migration, then you should pass the version of the migration in the following:

rake db:migrate:down VERSION=xxxxx

where xxxxx is the version number of the migration.

davmac
  • 18,558
  • 1
  • 32
  • 55
uma
  • 2,698
  • 22
  • 20
28

rake db:migrate:down VERSION=your_migrations's_version_number_here

The version is the numerical prefix on the migration's file name

How to find version:

Your migration files are stored in your rails_root/db/migrate directory. Find appropriate file up to which you want to rollback and copy the prefix number.

for example

file name: 20140208031131_create_roles.rb then the version is 20140208031131

Hardik
  • 3,558
  • 3
  • 29
  • 38
18

Rolling back last migration:

# rails < 5.0
rake db:rollback

# rails >= 5.0
rake db:rollback
# or
rails db:rollback

Rolling back last n number of migrations

# rails < 5.0
rake db:rollback STEP=2

# rails >= 5.0
rake db:rollback STEP=2
# or
rails db:rollback STEP=2

Rolling back a specific migration

# rails < 5.0
rake db:migrate:down VERSION=20100905201547

# rails >= 5.0
rake db:migrate:down VERSION=20100905201547
# or
rails db:migrate:down VERSION=20100905201547
Graham
  • 6,577
  • 17
  • 55
  • 76
Deepak Mahakale
  • 19,422
  • 8
  • 58
  • 75
14

To rollback the last migration you can do:

rake db:rollback

If you want to rollback a specific migration with a version you should do:

rake db:migrate:down VERSION=YOUR_MIGRATION_VERSION

If the migration file you want to rollback was called db/migrate/20141201122027_create_some_table.rb, then the VERSION for that migration is 20141201122027, which is the timestamp of when that migration was created, and the command to roll back that migration would be:

rake db:migrate:down VERSION=20141201122027
Deepak Mahakale
  • 19,422
  • 8
  • 58
  • 75
Sandip Vavhal
  • 140
  • 1
  • 7
9

To roll back all migrations up to a particular version (e.g. 20181002222222), use:

rake db:migrate VERSION=20181002222222

(Note that this uses db:migrate -- not db:migrate:down as in other answers to this question.)

Assuming the specified migration version is older than the current version, this will roll back all migrations up to, but not including, the specified version.

For example, if rake db:migrate:status initially displays:

  (... some older migrations ...)
  up      20181001002039  Some migration description
  up      20181002222222  Some migration description
  up      20181003171932  Some migration description
  up      20181004211151  Some migration description
  up      20181005151403  Some migration description

Running:

rake db:migrate VERSION=20181002222222

Will result in:

  (... some older migrations ...)
  up      20181001002039  Some migration description
  up      20181002222222  Some migration description
  down    20181003171932  Some migration description
  down    20181004211151  Some migration description
  down    20181005151403  Some migration description

Reference: https://makandracards.com/makandra/845-migrate-or-revert-only-some-migrations

Jon Schneider
  • 21,628
  • 17
  • 129
  • 157
6

If it is a reversible migration and the last one which has been executed, then run rake db:rollback. And you can always use version. e.g

the migration file is 20140716084539_create_customer_stats.rb,so the rollback command will be, rake db:migrate:down VERSION=20140716084539

Santanu
  • 910
  • 9
  • 13
4

From Rails Guide

Reverting Previous Migrations

You can use Active Record's ability to rollback migrations using the revert method:

require_relative '20100905201547_create_blocks'

class FixupCreateBlock < ActiveRecord::Migration
  def change
    revert CreateBlock

    create_table(:apples) do |t|
      t.string :variety
    end
  end
end

The revert method also accepts a block of instructions to reverse. This could be useful to revert selected parts of previous migrations. For example, let's imagine that CreateBlock is committed and it is later decided it would be best to use Active Record validations, in place of the CHECK constraint, to verify the zipcode.

    class DontUseConstraintForZipcodeValidationMigration < ActiveRecord::Migration
      def change
        revert do
          # copy-pasted code from CreateBlock
          reversible do |dir|
            dir.up do
              # add a CHECK constraint
              execute <<-SQL
                ALTER TABLE distributors
                  ADD CONSTRAINT zipchk
                    CHECK (char_length(zipcode) = 5);
              SQL
            end
            dir.down do
              execute <<-SQL
                ALTER TABLE distributors
                  DROP CONSTRAINT zipchk
              SQL
            end
          end

          # The rest of the migration was ok
        end
      end
    end

The same migration could also have been written without using revert but this would have involved a few more steps: reversing the order of create_table and reversible, replacing create_table by drop_table, and finally replacing up by down and vice-versa. This is all taken care of by revert.

Manish Shrivastava
  • 26,075
  • 13
  • 88
  • 100
3

Migrations change the state of the database using the command

$ bundle exec rake db:migrate

We can undo a single migration step using

  $ bundle exec rake db:rollback

To go all the way back to the beginning, we can use

  $ bundle exec rake db:migrate VERSION=0

As you might guess, substituting any other number for 0 migrates to that version number, where the version numbers come from listing the migrations sequentially

Nirupa
  • 767
  • 1
  • 7
  • 20
2

If you want to rollback and migrate you can run:

rake db:migrate:redo

That's the same as:

rake db:rollback
rake db:migrate
Iwan B.
  • 3,052
  • 2
  • 22
  • 15
2

Well in rails 5 it's quite easy rake db:migrate:status or rails db:migrate:status

It was modified to handle both the same way Then just pick which Version you want to roll back and then run rake db:migrate VERSION=2013424230423

Make sure VERSION is all capital letters

If you have a problem with any step of the migration or stuck in the middle simply go to the migration file and comment out the lines that were already migrated.

Hope that helps

Shahin
  • 1,447
  • 1
  • 10
  • 16
  • 1
    I highlight the hint for command **rake db:migrate:status** . . . It's great for overview to see the current execution state of the migration files. – Beauty Aug 01 '17 at 19:00
1

In Addition

When migration you deployed long ago does not let you migrate new one.

What happened is, I work in a larger Rails app with more than a thousand of migration files. And, it takes a month for us to ship a medium-sized feature. I was working on a feature and I had deployed a migration a month ago then in the review process the structure of migration and filename changed, now I try to deploy my new code, the build failed saying

ActiveRecord::StatementInvalid: PG::DuplicateColumn: ERROR:  column "my_new_field" of relation "accounts" already exists

none of the above-mentioned solutions worked for me because the old migration file was missing and the field I intended to create in my new migration file already existed in the DB. The only solution that worked for me is:

  1. I scped the file to the server
  2. I opened the rails console
  3. I required the file in the IRB session
  4. then AddNewMyNewFieldToAccounts.new.down

then I could run the deploy build again.

Hope it helps you too.

illusionist
  • 7,996
  • 1
  • 46
  • 63