Skip to content

Instantly share code, notes, and snippets.

@frankyston
Forked from andycamp/truncate_db_task.rb
Created December 25, 2018 17:17
Show Gist options
  • Save frankyston/2d42cf3c9403ceed1711c3101c5dc774 to your computer and use it in GitHub Desktop.
Save frankyston/2d42cf3c9403ceed1711c3101c5dc774 to your computer and use it in GitHub Desktop.
Rake Task for truncating all tables in a rails app. Preserves the schema_migrations.
desc "Truncate all tables in the database"
task :truncate_all_tables! => :environment do
unless Rails.env.production?
puts "TRUNCATING ALL TABLES in 3 seconds!!!!"
sleep 3
ActiveRecord::Base.connection.tables.each do |table|
unless table == "schema_migrations"
puts "Truncating #{table}."
ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table} RESTART IDENTITY CASCADE;")
else
puts "skipping schema_migrations table"
end
end
else
puts "This task is not available in production!!!! It will destroy all data in the database."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment