rake db:reset删除所有表但不删除数据库

Phi*_*shy 5 postgresql rake ruby-on-rails

我需要删除数据库中的所有表而不删除数据库,因为此数据库的用户没有create database特权.

删除所有表但不删除实际数据库的最佳方法是什么?

此外,我们使用rake db:seed一些表添加一些条目,所以我不想使用种子文件.

Phi*_*shy 8

这是我在查看Truncate方法后最终想出的解决方案.

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
Run Code Online (Sandbox Code Playgroud)

  • 如果有外键引用表,似乎会中断:( (2认同)