Search code examples
ruby-on-rails-4sqlitedbmigrate

Rake db:migrate error, table already exists


I accidentally create a migration which I did not need so I delete the file, and created a new migration now when I try to run rake db:migrate I keep getting this error. I am the using SQlite3 gem, and Ruby on Rails 4

StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "categories" already exists: CREATE TABLE "categories" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "category_name" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NO
T NULL) D:/muse/db/migrate/20150830113519_create_categories.rb:3:in `change'
D:in `migrate'
ActiveRecord::StatementInvalid: SQLite3::SQLException: table "categories" already exists: CREATE TABLE "categories" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "category_name" varchar, "created_at" datetime NO
T NULL, "updated_at" datetime NOT NULL)
D:/muse/db/migrate/20150830113519_create_categories.rb:3:in `change'
D:in `migrate'
SQLite3::SQLException: table "categories" already exists
D:/muse/db/migrate/20150830113519_create_categories.rb:3:in `change'
D:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

Solution

  • When you create a migration and run it, and want to make chances, you must first rollback:

    $ bin/rake db:rollback STEP=1

    At this stage you can delete the file or modify it and run again the migration_

    $ bin/rake db:migrate

    Now that you deleted the file, you cant rollback. What you have to do is delete the table manually or create a migration to drop that table:

    $ bin/rails generate migration DropCategoriesTable

    This will generate a migration file. Edit it:

    class DropCategoriesTable < ActiveRecord::Migration
      def up
        drop_table :categories
      end
    
      def down
        raise ActiveRecord::IrreversibleMigration
      end
    end