How to delete all data from all tables in Rails?

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

    Building up on @Vlad Zloteanu's answer, here is a version to remove all tables while keeping the user records and login sessions together with some meta information. Feel free to adjust the list of tables to your requirements.

    # lib/tasks/db/truncate.rake
    
    namespace :db do
      desc 'Truncate all tables except users state and meta'
      task truncate: :environment do
        conn = ActiveRecord::Base.connection
        tables = conn.tables - %w[
          sessions
          users
          roles
          users_roles
          schema_migrations
          ar_internal_metadata
        ]
        tables.each { |t| conn.execute("TRUNCATE #{t}") }
    
        puts "Truncated tables\n================\n#{tables.sort.join("\n")}"
      end
    end
    

提交回复
热议问题