How To Drop Table In Rails

In this article, we’ll assist you through a step by step approach to drop a table in rails using migration and the console approach. Firstly, let’s explore the migration method.

Drop Table in Rails with Migrations

Step 1: Generate a migration

Run rails generate migration RemoveYourTable in the terminal to create a new migration file.

rails generate migration RemoveYourTable

Step 2: Edit the Migration

Open the generated migration file and use drop_table command

class RemoveYourTable < ActiveRecord::Migration[6.0]
  def change
    drop_table :your_table_name
  end
end

Step 3: Run the Migration

Type rails db:migrate in terminal to apply the changes and drop table from your database.

rails db:migrate

Step 4: Confirm Removal

Check your schema file or use the Rails console to confirm the table removal.

Step 5: Update Codebase

Find and remove any references to the dropped table in your Rails application code.

Step 6: Restart Server

Restart your Rails server to ensure changes are made in database.

rails server

Second method of dropping a table using the Rails console.

Drop a Table through rails console

Step 1: Open Your Rails Console

Open Rails console in your terminal

rails console

Step 2: Navigate To Database

Navigate to your database in terminal

ActiveRecord::Base.connection

Step 3: List Existing Tables

Type ActiveRecord::Base.connection.tables in rails console and click enter.

ActiveRecord::Base.connection.tables

Step 4: Confirm Table Presence

Double-check to ensure your target table is in the list.

Step 5: Drop The Table

Type ActiveRecord::Migration.drop_table(:your_table_name)
 in rails console and click enter.

ActiveRecord::Migration.drop_table(:your_table_name)

Step 6: Confirm Deletion

Double check the tables the desired table is removed from database.

ActiveRecord::Base.connection.tables

Step 7: Exit Console

Type exit to leave the Rails console

Step 8: Update Your Codebase

Remove references to the dropped table in your Rails code.

Step 9: Restart Your Server

rails server

For other queries checkout rails documentation for dropping a table or need any assistance from our developers visit evolwix 

Leave a Reply

Your email address will not be published. Required fields are marked *