Phillip Boushy
Phillip Boushy

Reputation: 465

rake db:reset Drop all tables but not database

I need to drop all the tables in my database without dropping the database because the user for this database does not have create database privileges.

What is the best way to drop all the tables but not the actual database?

Also, we use rake db:seed to add some entries into one of the tables so I don't want to use a seed file.

Upvotes: 5

Views: 6226

Answers (5)

benr75
benr75

Reputation: 312

To solve for:

PG::DependentObjectsStillExist: ERROR: cannot drop table location_types because other objects depend on it

Force a CASCADE.

namespace :db do
  desc "Erase all tables"
  task :clear => :environment do
    conn = ActiveRecord::Base.connection
    tables = conn.tables
    tables.each do |table|
      puts "Deleting #{table}"
      conn.drop_table(table, force: :cascade)
    end
  end
end

Upvotes: 1

Phillip Boushy
Phillip Boushy

Reputation: 465

This is the solution I eventually came up with after looking at the Truncate method.

namespace :db do
  desc "Erase all tables"
  task :clear => :environment do
    conn = ActiveRecord::Base.connection
    tables = conn.tables
    tables.each do |table|
      puts "Deleting #{table}"
      conn.drop_table(table)
    end
  end
end

Upvotes: 9

manu29.d
manu29.d

Reputation: 1568

for testing, i would suggest using:

rake db:test:prepare

It will re-generate all your tables based on your db/schema.rb

Upvotes: 2

davidinjc
davidinjc

Reputation: 61

If you run rake -P | grep db you will see all the database tasks built into Rails, but none of them seem to do what you're looking for. I believe the only way to do it is using a migration. This answer shows you how.

Upvotes: 0

JGutierrezC
JGutierrezC

Reputation: 4523

You could achieve that with the following rake task (which i found here time ago)

namespace :db do
  desc "Truncate all tables"
  task :truncate => :environment do
    conn = ActiveRecord::Base.connection
    tables = conn.execute("show tables").map { |r| r[0] }
    tables.delete "schema_migrations"
    tables.each { |t| conn.execute("TRUNCATE #{t}") }
  end
end

Edited to add a link to the question i found before:

Delete everything from all tables (in Activerecord)

I don't understand why you want to drop all tables if the truncate instruction also make a fresh start of your table.

Anyway, maybe this answers could be helpful too:

https://stackoverflow.com/a/2789515/1639291

https://stackoverflow.com/a/1197218/1639291

Upvotes: 0

Related Questions