The purpose of creating migrations is to alter or modify the data in our database. Using migration is more easier that writing SQL commands to create, add or remove tables, columns or entries to the database schema. For this blog I am going to show you how to create migrations using rake tasks.
Let's say we want to create a table to store users information for a web application.
- First, we will run this command:
$ rake db:create_migration NAME=create_users_table
By running this command a new file will be generated in db/migrations that will be called 20221026_create_users_table. The beginning of the files name is the timestamp of when the file was created so that the migrations can run in the correct order.
- Now, lets take a look at the new migration file that we just created:
Here we have a class called CreateUsersTable and it inherits from Active Records Migration module. Inside the class there is a method called change, this method is used to update the database schema.
- Next, inside the method change we will create a new table called "users" like this:
Here we add the create_table method and we passed the name of the table we are creating as a symbol and then we write a code block with the columns names and their types for our table "users".
- Lastly, all we have to do is run the migrations by running this command in the console:
$ rake db:migrate
After running this command the database will be generated along side a new file called schema.rb which will contain the skeleton of our database.
Lets take a look:
If we want to update our database schema to add a column that we forgot to add in our first migration we will need to create a new migration file like this:
We create a new migration:
$ rake db:create_migration NAME=add_column_to_users
We then add a column:
Then we run the migration
$ rake db:migrate
And now we can see our new added column called address to our schema file.
Top comments (0)