How to Drop a Table in Rails

December 7, 2021   • 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 plan to use it anymore. How do you remove that table?

Let’s assume you used the following generator script to create the table articles.

➜ bin/rails generate migration CreateArticles title:string body:text

Then, you ran the migration.

➜ bin/rails db:migrate

To remove this table, you will follow the opposite process.

Step 1: Generate a migration that drops the table. The following command creates an empty migration file.

➜  blog (main) ✗ bin/rails generate migration DropArticles

Step 2: Now, use the drop_table method, providing the table’s name. This method tells 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

Congratulations, you just dropped the table.

Additionally, you can provide the following options to the drop_table call.

  • :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

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 6.1.4.1)

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 >

If you change your mind again and want to recreate the table, reverse the migration using db:rollback.

➜  bin/rails db:rollback

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.

Anyway, hope that helps!