How to delete all data from all tables in Rails?

前端 未结 16 2389
情歌与酒
情歌与酒 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

    If you simply want to start fresh with a fresh set of empty tables, you can first ensure you have an up-to-date definition of the schema in db/schema.rb:

    rake db:schema:dump
    

    and then:

    rake db:schema:load
    

    which has the effect of dropping tables and then re-creating them, without running through your entire battery of migrations.

    0 讨论(0)
  • 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") }
    
    0 讨论(0)
  • 2020-12-07 16:25

    rails db:purge

    has recently been added to ActiveRecord in the master branch of rails 4.2.0.alpha

    https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d

    0 讨论(0)
  • 2020-12-07 16:25

    My 50 cents, for cleaning db and able to run migrations again (in cases when you can't delete database, eg AWS RDS):

    # get connection
    conn = ActiveRecord::Base.connection
    # find all tables needed to be removed
    tables = conn.execute("SELECT * FROM pg_catalog.pg_tables WHERE schemaname='public' AND tablename<>'schema_migrations'").to_a.map { |r| r['tablename'] }
    # remove all tables except schema_migrations
    tables.each { |t| conn.execute("DROP TABLE #{t}") }
    # clean migrations table
    conn.execute("TRUNCATE TABLE schema_migrations")
    

    And now you can run rake db:migrate to have your db in a clean state.

    0 讨论(0)
提交回复
热议问题