Skip to content

Instantly share code, notes, and snippets.

@andycamp
Created January 30, 2014 16:41
Show Gist options
  • Select an option

  • Save andycamp/8712864 to your computer and use it in GitHub Desktop.

Select an option

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.
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
@ianheggie
Copy link
Copy Markdown

I altered the guts for later versions of rails and MySQL as follows (I use this in test_helper):

def truncate_all_tables!
    connection = ActiveRecord::Base.connection
    connection.execute 'SET FOREIGN_KEY_CHECKS = 0'
    connection.tables.each do |table|
      if %w[ar_internal_metadata schema_migrations].include? table
        puts "skipping #{table} table"
      else
        puts "Truncating #{table}."
        connection.execute("TRUNCATE TABLE #{table}")
        connection.execute("ALTER TABLE #{table} AUTO_INCREMENT = 1")
      end
    end
    connection.execute 'SET FOREIGN_KEY_CHECKS = 1'
  end

@minimul
Copy link
Copy Markdown

minimul commented Aug 11, 2023

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