How to delete all data from all tables in Rails?

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

    We have been remiss here at Stack Overflow for not mentioning the database_cleaner gem:

    Database Cleaner is a set of strategies for cleaning your database in Ruby. The original use case was to ensure a clean state during tests. Each strategy is a small amount of code but is code that is usually needed in any ruby app that is testing with a database.

    By 'strategy', Mr. Mabey means: truncation, transaction, and deletion.

    ActiveRecord, DataMapper, Sequel, MongoMapper, Mongoid, and CouchPotato are supported.

    Here is a quick code snippet from the Database Cleaner README:

    require 'database_cleaner'
    DatabaseCleaner.strategy = :truncation
    
    # then, whenever you need to clean the DB
    DatabaseCleaner.clean
    

提交回复
热议问题