How to delete all data from all tables in Rails?

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

    If you're trying to do this from code instead of the command line, say from a Test::Unit::TestCase#teardown method, you could do either

    class MyTest < Test::Unit::TestCase
    
      def teardown
        ActiveRecord::Base.subclasses.each(&:delete_all)
      end
    
    end
    

    or

    class MyTest < Test::Unit::TestCase
    
      def teardown
        Rake::Task['db:reset'].invoke
      end
    
    end
    

    I warn you, though: neither is particularly fast. You're definitely better off with transactional tests if you can.

提交回复
热议问题