Rails DB Migration - How To Drop a Table?
You won't always be able to simply generate the migration to already have the code you want. You can create an empty migration and then populate it with the code you need.
You can find information about how to accomplish different tasks in a migration here:
http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
More specifically, you can see how to drop a table using the following approach:
drop_table :table_name
First generate an empty migration with any name you'd like. It's important to do it this way since it creates the appropriate date.
rails generate migration DropProductsTable
This will generate a .rb file in /db/migrate/ like 20111015185025_drop_products_table.rb
Now edit that file to look like this:
class DropProductsTable < ActiveRecord::Migration
def up
drop_table :products
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
The only thing I added was drop_table :products
and raise ActiveRecord::IrreversibleMigration
.
Then run rake db:migrate
and it'll drop the table for you.
Write your migration manually. E.g. run rails g migration DropUsers
.
As for the code of the migration I'm just gonna quote Maxwell Holder's post Rails Migration Checklist
BAD - running rake db:migrate
and then rake db:rollback
will fail
class DropUsers < ActiveRecord::Migration
def change
drop_table :users
end
end
GOOD - reveals intent that migration should not be reversible
class DropUsers < ActiveRecord::Migration
def up
drop_table :users
end
def down
fail ActiveRecord::IrreversibleMigration
end
end
BETTER - is actually reversible
class DropUsers < ActiveRecord::Migration
def change
drop_table :users do |t|
t.string :email, null: false
t.timestamps null: false
end
end
end
Warning: Do this at your own risk, as @z-atef and @nzifnab correctly point out, Rails will not be aware of these changes, your migration sequence fill fail and your schema will be different from your coworkers'. This is meant as a resource for locally tinkering with development only.
While the answers provided here work properly, I wanted something a bit more 'straightforward', I found it here: link First enter rails console:
$rails console
Then just type:
ActiveRecord::Migration.drop_table(:table_name)
And done, worked for me!