niaomingjian niaomingjian - 1 month ago 15
Ruby Question

How to undo the action of rails db:migrate in Rails 5.0.0.1

When migrating the database, I made a spelling mistake.

I want to generate a scaffold by running:

rails generate scaffold Micropost context:text user_id:integer
rails db:migrate


Although I made a mistake by leaving out the colon when I ran:

rails generate scaffold Micropost context:text user_id integer
rails db:migrate


I want to undo this migration, how to do it?
(I'm using Rails
5.0.0.1
)

When I run
rails db:migrate
, I get an error of:

SQLite3::SQLException: table "microposts" already exists:


When I run
rails db:migrate:status
, I get the following output:

Status Migration ID Migration Name
up 20161024021157 Create users
up 20161024025545 ********** NO FILE **********
down 20161024025805 Create microposts


I tried to use
rails db:migrate:down VERSION=20161024025805
. There wasn't any message showing in the command line. Then I ran
rails db:migrate
. The error is the same.

Answer

rails db:rollback will simply rollback one migration which I believe is what you are looking for

For a more specific rollback, you can run rails db:migrate:down VERSION=numberofversion

Replace the numberofversion with the version number of the migration file generated, for example:

rails db:migrate:down VERSION=1843652238

Edit:

Since you are getting the error that the Microposts table already exists, you must follow these steps to remove the table:

  1. Run rails generate migration DropMicroposts
  2. Go to the /db/migrate folder and find the latest migration file you just created
  3. In that file paste this:

    class DropMicroposts < ActiveRecord::Migration 
      def up 
        drop_table :microposts 
      end 
    end 
    
  4. run rails db:migrate

  5. After this, run rails generate scaffold Micropost context:text user_id:integer
  6. Then run rails db:migrate
Comments