How to delete all data from all tables in Rails?

前端 未结 16 2410
情歌与酒
情歌与酒 2020-12-07 15:23

I can do Post.delete_all to delete all my posts, but what if I want to delete all posts, comments, blogs, etc.?

How do I iterate over all my models and

16条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 16:24

    Accepted answer with Postgres db:

    namespace :db do
      desc "Truncate all tables"
      task :truncate => :environment do
        conn = ActiveRecord::Base.connection
        postgres = "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname='public'"
        tables = conn.execute(postgres).map { |r| r['tablename'] }
        tables.delete "schema_migrations"
        tables.each { |t| conn.execute("TRUNCATE \"#{t}\"") }
      end
    end
    

    If there are foreign_key error like ActiveRecord::StatementInvalid (PG::FeatureNotSupported: ERROR: cannot truncate a table referenced in a foreign key constraint)

    Then, CASCADE option would help.

    tables.each { |t| conn.execute("TRUNCATE \"#{t}\" CASCADE") }
    

提交回复
热议问题