- Read Tutorial
- Watch Guide Video
Rake is a utility built into both Ruby and Rails that allows you to do a set of common administration tasks. In this lesson, we are going to see how you can use rake options to manage your database.
Here is the complete list of the database-related rake commands that you will use.
db:create
- It creates the database for the current environment.
db:create:all
- It creates the database for all environments.
db:drop
- It drops or deletes the database for the current environment.
db:drop:all
- It drops the database for all environments.
db:migrate
- It runs migrations for the current environment. This is a common command that you will use. Every time you migrate a database or make any change to it such as adding a row or a column, adding a table or changing data type, you have to run this command for the changes to reflect in your database.
db:migrate:up
- It runs a specific migration
db:migrate:down
- It rolls back a specific migration. You can use it when you have made a mistake or want to make changes to the last migration.
db:migrate:status
- It shows the status of the current migration
db:rollback
- It does a complete roll back to the last migration file.
db:forward
- It is used when you want to move to the next version. I rarely use it.
db:seed
- It helps to create seed data that you can use for testing. So, you can create a set of data, store it in the seed.rb file and run this command, and it will load all the test data into your application.
db:schema:load
- This command create a schema file that mimics your database, so your schema file looks like that file. It then loads this schema file into your current environment.
db:schema:dump
- It drops and deletes the schema in your current environment
db:setup
- It runs db:schema:load and db:seed. I use this command when I start a brand new application to test different database models. The advantage with this command is it will wipe out the database completely including the data that I no longer want and will run the new schema with test data loaded in the seed file.
db:reset
- It runs db:drop to delete everything and db:setup to start everything from scratch.
db:migrate:redo
- This command runs whatever you put in the migration file, and can include db:migrate:down, db:migrate:up and db:rollback. I rarely use this complex command.
db:migrate:reset
- It runs db:drop, db:create and db:migrate
Out of these different rake db commands, db:create
, db:migrate
, db:seed
and db:setup
are the ones that you will use a lot. Be careful when you use db:setup
, as it can wipe out a database and all the data in it. Never use it on a production database in a live environment, unless you know for sure there is no data.