[ruby-on-rails] 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?

This question is related to ruby-on-rails database ruby-on-rails-3 migration rake

The answer is


ActiveRecord::Base.connection.drop_table :table_name


if you want to drop a specific table you can do

$ rails db:migrate:up VERSION=[Here you can insert timestamp of table]

otherwise if you want to drop all your database you can do

$rails db:drop

Open you rails console

ActiveRecord::Base.connection.execute("drop table table_name")

If you want to delete the table from the schema perform below operation --

rails db:rollback

I wasn't able to make it work with migration script so I went ahead with this solution. Enter rails console using the terminal:

rails c

Type

ActiveRecord::Migration.drop_table(:tablename)

It works well for me. This will remove the previous table. Don't forget to run

rails db:migrate

if anybody is looking for how to do it in SQL.

type rails dbconsole from terminal

enter password

In console do

USE db_name;

DROP TABLE table_name;

exit

Please dont forget to remove the migration file and table structure from schema


Run this command:-

rails g migration drop_table_name

then:

rake db:migrate

or if you are using MySql database then:

  1. login with database
  2. show databases;
  3. show tables;
  4. drop table_name;

Drop Table/Migration

run:- $ rails generate migration DropTablename

exp:- $ rails generate migration DropProducts


  1. rails g migration drop_users
  2. edit the migration
    class DropUsers < ActiveRecord::Migration
      def change
        drop_table :users do |t|
          t.string :name
          t.timestamps
        end
      end
    end
  1. rake db:migrate

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
  end
end

GOOD - reveals intent that migration should not be reversible

class DropUsers < ActiveRecord::Migration
  def up
    drop_table :users
  end

  def down
    fail ActiveRecord::IrreversibleMigration
  end
end

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
  end
end

I needed to delete our migration scripts along with the tables themselves ...

class Util::Table < ActiveRecord::Migration

 def self.clobber(table_name)   
    # drop the table
    if ActiveRecord::Base.connection.table_exists? table_name
      puts "\n== " + table_name.upcase.cyan + " ! " 
           << Time.now.strftime("%H:%M:%S").yellow
      drop_table table_name 
    end

    # locate any existing migrations for a table and delete them
    base_folder = File.join(Rails.root.to_s, 'db', 'migrate')
    Dir[File.join(base_folder, '**', '*.rb')].each do |file|
      if file =~ /create_#{table_name}.rb/
        puts "== deleting migration: " + file.cyan + " ! "
             << Time.now.strftime("%H:%M:%S").yellow
        FileUtils.rm_rf(file)
        break
      end
    end
  end

  def self.clobber_all
    # delete every table in the db, along with every corresponding migration 
    ActiveRecord::Base.connection.tables.each {|t| clobber t}
  end

end

from terminal window run:

$ rails runner "Util::Table.clobber 'your_table_name'"

or

$ rails runner "Util::Table.clobber_all"

you can simply drop a table from rails console. first open the console

$ rails c

then paste this command in console

ActiveRecord::Migration.drop_table(:table_name)

replace table_name with the table you want to delete.

you can also drop table directly from the terminal. just enter in the root directory of your application and run this command

$ rails runner "Util::Table.clobber 'table_name'"

The simple and official way would be this:

  rails g migration drop_tablename

Now go to your db/migrate and look for your file which contains the drop_tablename as the filename and edit it to this.

    def change
      drop_table :table_name
    end

Then you need to run

    rake db:migrate 

on your console.


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.


I think, to be completely "official", you would need to create a new migration, and put drop_table in self.up. The self.down method should then contain all the code to recreate the table in full. Presumably that code could just be taken from schema.rb at the time you create the migration.

It seems a little odd, to put in code to create a table you know you aren't going to need anymore, but that would keep all the migration code complete and "official", right?

I just did this for a table I needed to drop, but honestly didn't test the "down" and not sure why I would.


You need to to create a new migration file using following command

rails generate migration drop_table_xyz

and write drop_table code in newly generated migration file (db/migration/xxxxxxx_drop_table_xyz) like

drop_table :tablename

Or if you wanted to drop table without migration, simply open rails console by

$ rails c

and execute following command

ActiveRecord::Base.connection.execute("drop table table_name")

or you can use more simplified command

ActiveRecord::Migration.drop_table(:table_name)

You can roll back a migration the way it is in the guide:

http://guides.rubyonrails.org/active_record_migrations.html#reverting-previous-migrations

Generate a migration:

rails generate migration revert_create_tablename

Write the migration:

require_relative '20121212123456_create_tablename'

class RevertCreateTablename < ActiveRecord::Migration[5.0]
  def change
    revert CreateTablename    
  end
end

This way you can also rollback and can use to revert any migration


the best way you can do is

rails g migration Drop_table_Users

then do the following

rake db:migrate

While the answers provided here work properly, I wanted something a bit more 'straightforward', I found it here: link First enter rails console:

$rails console

Then just type:

ActiveRecord::Migration.drop_table(:table_name)

And done, worked for me!


Alternative to raising exception or attempting to recreate a now empty table - while still enabling migration rollback, redo etc -

def change
  drop_table(:users, force: true) if ActiveRecord::Base.connection.tables.include?('users')
end

Run

rake db:migrate:down VERSION=<version>

Where <version> is the version number of your migration file you want to revert.

Example:-

rake db:migrate:down VERSION=3846656238

Examples related to ruby-on-rails

Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Where do I put a single filter that filters methods in two controllers in Rails Empty brackets '[]' appearing when using .where How to integrate Dart into a Rails app Rails 2.3.4 Persisting Model on Validation Failure How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Rails: Can't verify CSRF token authenticity when making a POST request Uncaught ReferenceError: React is not defined

Examples related to database

Implement specialization in ER diagram phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' cannot be loaded Room - Schema export directory is not provided to the annotation processor so we cannot export the schema SQL Query Where Date = Today Minus 7 Days MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server date format yyyymmdd How to create a foreign key in phpmyadmin WooCommerce: Finding the products in database TypeError: tuple indices must be integers, not str

Examples related to ruby-on-rails-3

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? rake assets:precompile RAILS_ENV=production not working as required How do you manually execute SQL commands in Ruby On Rails using NuoDB Check if record exists from controller in Rails How to restart a rails server on Heroku? How to have a drop down <select> field in a rails form? "Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application Adding a simple spacer to twitter bootstrap How can I change cols of textarea in twitter-bootstrap? Rails: FATAL - Peer authentication failed for user (PG::Error)

Examples related to migration

Want to upgrade project from Angular v5 to Angular v6 Laravel 5.4 Specific Table Migration SQLSTATE[HY000] [2002] Connection refused within Laravel homestead Laravel migration table field's type change How can I rename column in laravel using migration? Warning about `$HTTP_RAW_POST_DATA` being deprecated Entity Framework rollback and remove bad migration Migration: Cannot add foreign key constraint Maven is not working in Java 8 when Javadoc tags are incomplete Rails: Adding an index after adding column

Examples related to rake

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources Difference between rake db:migrate db:reset and db:schema:load Rails and PostgreSQL: Role postgres does not exist What does bundle exec rake mean? "Could not find bundler" error Rails how to run rake task How to rollback just one step using rake db:migrate Purge or recreate a Ruby on Rails database Rails DB Migration - How To Drop a Table? how to do "press enter to exit" in batch