How to delete all data from all tables in Rails?

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

    If you want to delete only the data without touching the tables while using it inside your application or rails console :

    Rails.application.eager_load!
    ActiveRecord::Base.connection.disable_referential_integrity do
      ApplicationRecord.descendants.each do |model|
        model.delete_all
      end
    end
    

    With this code, you don't have to bother with referencing manually your models and/or with foreign key constraints (thanks to disable_referential_integrity).
    ApplicationRecord.descendants returns only true application models unlike ActiveRecord::Base.descendants (no more ApplicationRecord, schema_migrations and ar_internal_metadata).

提交回复
热议问题