Last Updated: September 09, 2019
·
6.636K
· subosito

Faster way to reset database entries

For many cases, we want to delete all entries on database. We can drop the db and then re-setup it, remember rake db:reset or rake db:drop && rake db:create && rake db:migrate.

I think rather than recreating database only to remove all the database entries, truncate the database is better way to go. To do so, add the snippet into lib/tasks/db.rake:

namespace :db do

  desc 'Truncate all tables, except schema_migrations (customizable)'
  task :truncate, [ :tables ] => 'db:load_config' do |t, args|
    args.with_defaults(tables: 'schema_migrations')

    skipped = args[:tables].split(' ')
    config  = ActiveRecord::Base.configurations[::Rails.env]

    ActiveRecord::Base.establish_connection
    ActiveRecord::Base.connection.tables.each do |table|
      ActiveRecord::Base.connection.execute("TRUNCATE #{table}") unless skipped.include?(table)
    end
  end

end

Then we can simply run:

rake db:truncate

If we want to to skip certain tables we can run as:

rake db:truncate[schema_migrations users profiles]

2 Responses
Add your response

Both MySQL and PostgreSQL are supported?

over 1 year ago ·

@sheerun Yes, they are. While using this, please be be careful of foreign key constraints, sometime it's prevent truncation process because of reference error.

over 1 year ago ·