How to Drop a Table in Rails
So you created a migration to add a table that you thought you were going to need. You also ran that migration so that table is in your database. Now, you don’t need it anymore and want to drop it from the database. How do you remove that table?
Step 1: Generate a migration
Run the following command to create a new migration named
articles is the table name.
➜ blog (main) ✗ bin/rails generate migration DropArticles
Step 2: Use the drop_table method
The drop_table method takes the table name as an argument and instructs rails to drop that table from the database when running the migration.
class DropArticles < ActiveRecord::Migration[6.1] def change drop_table :articles end end
Step 3: Run the migration
To execute the above code to drop the table, run the database migration.
➜ blog (main) ✗ bin/rails db:migrate
Congratulations, you just dropped the table. If you change your mind again and want to recreate the table, reverse the migration using the
Warning: Remember that fully reversing this migration is not possible. So if you rollback this migration, Rails will create an empty table. When you drop a table, you also get rid of all the data it contains. You won’t get back the data the table had before deletion.
You can provide the following options to the
:force: Use it to drop dependent objects by setting the value to
:cascade. It defaults to false.
drop_table :articles, force: :cascade
if_exists: Set it to true, to only drop the table if it exists. It defaults to false, too.
drop_table :articles, if_exists: true
Drop table without migration
There is another way to drop the table without using a migration. Enter the rails console, and tell the
ActiveRecord::Migration class to drop that table.
➜ bin/rails c Running via Spring preloader in process 97140 Loading development environment (Rails 22.214.171.124) 3.0.2 :001 > ActiveRecord::Migration.drop_table :articles -- drop_table(:articles) (20.0ms) DROP TABLE "articles" -> 0.0980s => #<PG::Result:0x00007fa5d7ee21e8 status=PGRES_COMMAND_OK ntuples=0 nfields=0 cmd_tuples=0> 3.0.2 :002 >
I hope that helps! Let me know if you have any questions.
If you liked this post, you might enjoy these ones, too.