Created
January 30, 2014 16:41
-
-
Save andycamp/8712864 to your computer and use it in GitHub Desktop.
Rake Task for truncating all tables in a rails app. Preserves the schema_migrations.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
If using Database Cleaner. Also this approach does not yield Environment data not found in the schema. To resolve this issue, run:
error when running db:seed:replant
after.
# lib/tasks/truncate_and_reset.rake
desc "Truncate all tables in the database and reset their primary indexes"
task :truncate_and_reset => :environment do
return "Cannot run in production as all tables will be truncated!" if Rails.env.production?
require 'database_cleaner/active_record'
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean
puts 'All tables truncated and primary indexes reset'
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I altered the guts for later versions of rails and MySQL as follows (I use this in test_helper):