How to delete all data from all tables in Rails?

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

    A faster way to just delete table rows is to use the TRUNCATE command.

    Many of the other answers seem to ignore the difference between deleting rows and dropping a table. Dropping a table destroys the table data and schema; meaning that you need extra steps to recreate the tables. Sean McLeary's answer was the best I saw, so I used it as a starting point. However, I think it is better to take advantage of the TRUNCATE command, because it should be faster and it also resets auto-increment keys. Also, using map instead of each shortens the code a bit.

    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
    

提交回复
热议问题