How to delete all data from all tables in Rails?

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

    # fast truncation of all tables that need truncations (select is 10x faster then truncate)
    # http://grosser.it/2012/07/03/rubyactiverecord-fastest-way-to-truncate-test-database/
    def truncate_all_tables
      connection = ActiveRecord::Base.connection
      connection.disable_referential_integrity do
        connection.tables.each do |table_name|
          next if connection.select_value("SELECT count(*) FROM #{table_name}") == 0
          connection.execute("TRUNCATE TABLE #{table_name}")
        end
      end
    end
    

提交回复
热议问题