Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails DB Migration - How To Drop a Table?

I added a table that I thought I was going to need, but now no longer plan on using it. How should I remove that table?

I've already run migrations, so the table is in my database. I figure rails generate migration should be able to handle this, but I haven't figured out how yet.

I've tried:

rails generate migration drop_tablename 

but that just generated an empty migration.

What is the "official" way to drop a table in Rails?

like image 931
Jason Whitehorn Avatar asked Oct 26 '10 01:10

Jason Whitehorn


People also ask

How do you delete a table from schema?

DROP TABLE removes tables from the database. Only the table owner, the schema owner, and superuser can drop a table. To empty a table of rows without destroying the table, use DELETE or TRUNCATE . DROP TABLE always removes any indexes, rules, triggers, and constraints that exist for the target table.


2 Answers

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 
like image 167
Pete Avatar answered Oct 02 '22 12:10

Pete


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.

like image 37
Brandon O'Rourke Avatar answered Oct 02 '22 10:10

Brandon O'Rourke