o06qha
Last Updated: February 25, 2016
·
2.947K
· subosito
B8d0a61ecf3b9a23540703024875d7b7

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]
Say Thanks
Respond

2 Responses
Add your response

2879
Photo on 08.01.2013 at 04.15

Both MySQL and PostgreSQL are supported?

over 1 year ago ·
2883
B8d0a61ecf3b9a23540703024875d7b7

@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 ·