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 endend
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 endend
GOOD - reveals intent that migration should not be reversible
class DropUsers < ActiveRecord::Migration def up drop_table :users end def down fail ActiveRecord::IrreversibleMigration endend
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 endend