Work
with us

Tell us about your idea
and we will find a way
to make it happen.

Get estimate

Join our awesome team

Check offers

Let’s say you need to quickly clear the MySQL database and then import data from the seeds.

What are your tools? Let’s check with bundle exec rake -T

...
rake db:create                                      # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databases in the c...
rake db:drop                                        # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config)
rake db:fixtures:load                               # Load fixtures into the current environment's database
rake db:migrate                                     # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:status                              # Display status of migrations
rake db:rollback                                    # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear                          # Clear a db/schema_cache.dump file
rake db:schema:cache:dump                           # Create a db/schema_cache.dump file
rake db:schema:dump                                 # Create a db/schema.rb file that is portable against any DB supported by AR
rake db:schema:load                                 # Load a schema.rb file into the database
rake db:seed                                        # Load the seed data from db/seeds.rb
rake db:setup                                       # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the database first)
rake db:structure:dump                              # Dump the database structure to db/structure.sql
rake db:version                                     # Retrieves the current schema version number
...

Yes, you can rake db:drop && rake db:create && rake db:migrate && rake:db:seed or rake:db:reset but what if you only need to clean the database and quickly update the data from seeds.rb without wasting time with drop, migration, etc?

Simplify your life through libs.

Let’s do it!

Create a new file: lib/task/db.rake

# @author Pawel Przymusiala  <p.przymusiala::binarapps.com>
namespace :db do

  desc 'Truncate all tables except schema_migrations and import seeds'
  task :truncate => "db:load_config" do
      config = ActiveRecord::Base.configurations[::Rails.env]
      ActiveRecord::Base.establish_connection
      tables = ActiveRecord::Base.connection.tables - ['schema_migrations']
      print "Truncating tables (except schema_migrations), please wait"
      tables.each do |table|
        ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
        print "."
      end
      print " [ \e[0;32m OK \e[0m ]"
      print "\nSeeding tables, please wait..."
      Rake::Task["db:seed"].invoke
      print " [ \e[0;32m OK \e[0m ]\n"
      puts "Done."
    end
end

General info and useful tips

Attaching other tasks:

Rake::Task["db:seed"].invoke

Or maybe you need to modify this task a little? For example, specify which tables to skip?

task :truncate, [ :tables ] => 'db:load_config' do |t, args|
  args.with_defaults(tables: 'schema_migrations')
  skip = args[:tables].split(' ')

(...)

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

Do you use DatabaseCleaner gem?

DatabaseCleaner.strategy = :truncation, {:except => ['schema_migrations']}
DatabaseCleaner.clean

Another way? Modify your seeds.rb file

case Rails.env
  when "development"
  # truncate stuff :)
end

What next, how to get it running?

Run a terminal, go to your project dir, type rake db:truncate

$ rake db:truncate

Truncating tables (except schema_migrations), please wait.......................... [  OK  ]
Seeding tables, please wait... [  OK  ]
Done.

BTW: for backup&restore database: rake db:backup & rake db:backup:restore

# database config
  config = Rails.application.config
  database = config.database_configuration[Rails.env]["database"]
  username = config.database_configuration[Rails.env]["username"]
  password = config.database_configuration[Rails.env]["password"]

  # rake db:backup
  desc 'Create backup database to a sql file'
  task :backup => :environment do
    print "Creating #{database}_backup.sql, please wait..."
    `mysqldump -u "#{username}" --password="#{password}" "#{database}" > "#{database}"_backup.sql`
    print " [ \e[0;32m OK \e[0m ]\n"
    puts "Done."
  end

  namespace :backup do
    # rake db:backup:restore
    desc 'Restore database from backup file'

    task :restore do
      print "Restoring #{database}_backup.sql, please wait..."
      `mysql -u "#{username}" --password="#{password}" "#{database}" < "#{database}"_backup.sql`
      print " [ \e[0;32m OK \e[0m ]\n"
      puts "Done."
    end
  end

New tasks in action: Backup db: `rake db:backup

$ rake db:backup
Creating example_development_backup.sql, please wait... [  OK  ]
Done.

and restore rake db:backup:restore

$ rake db:backup:restore
Restoring example_development_backup.sql, please wait... [  OK  ]
Done.

Summary

Completed file lib/task/db.rake from this post:

# @author Pawel Przymusiala  <p.przymusiala::binarapps.com>
namespace :db do
  # commands list:
  # rake db:truncate        - clear db & import seeds
  # rake db:backup          - dump db to a sql file
  # rake db:backup:restore  - restore db from a sql file

  # database config
  config   = Rails.application.config
  database = config.database_configuration[Rails.env]["database"]
  username = config.database_configuration[Rails.env]["username"]
  password = config.database_configuration[Rails.env]["password"]

  # rake db:truncate
  desc 'Truncate all tables except schema_migrations and import seeds'
  task :truncate => "db:load_config" do
      ActiveRecord::Base.establish_connection
      tables = ActiveRecord::Base.connection.tables - ['schema_migrations']
      print "Truncating tables (except schema_migrations), please wait"
      tables.each do |table|
        ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
        print "."
      end
      print " [ \e[0;32m OK \e[0m ]"
      print "\nSeeding tables, please wait..."
      Rake::Task["db:seed"].invoke
      print " [ \e[0;32m OK \e[0m ]\n"
      puts "Done."
    end

  # rake db:backup
  desc 'Create backup database to a sql file'
  task :backup => :environment do
    print "Creating #{database}_backup.sql, please wait..."
    `mysqldump -u "#{username}" -p"#{password}" "#{database}" > "#{database}"_backup.sql`
    print " [ \e[0;32m OK \e[0m ]\n"
    puts "Done."
  end

  namespace :backup do
    # rake db:backup:restore
    desc 'Restore database from backup file'

    task :restore do
      print "Restoring #{database}_backup.sql, please wait..."
      `mysql -u "#{username}" -p"#{password}" "#{database}" < "#{database}"_backup.sql`
      print " [ \e[0;32m OK \e[0m ]\n"
      puts "Done."
    end
  end

That’s all. Enjoy!

Post tags: