How does a Ruby on Rails migration work?
Ruby on Rails is a web development framework, it has an MVC architecture, one of the functions of this framework are migrations.
Migrations help you to make changes into your database schema, they can execute different method o manage a database, and also supports the basic data types.
To create a migration, you should execute this command:
rails generate migration table_name
But, how does Rails actually generate this migration?
The next piece of code is the one that creates the migration file.
It basically does this:
- Generates a name for the file.
- Validates that an identical migration doesn’t exist.
- Create a file
In this link, you can see the complete file.
We can see in line 10 that thecreate_migration
function is called, this function calls the CreateMigration class that helps to validate the inexistence of an identical method.
You can see the complete file here.
After the migration file is created, you can add all the fields you need for your database, and run the next command to generate the database.
rake db:migrate
This file is the one in charge to migrate (create) the database, in this piece of code we can find the database connections and executes the ActiveRecord::Tasks::DatabaseTasks.migrate function.
Now, talking about ActiveRecord::Tasks::DatabaseTasks
(here is the file) it encapsulates logic behind some common tasks used to manage database migrations, and themigrate
function is the one that actually do the migrations.
There are lots of files where to dig, but this was a basic explanation about how the Ruby on Rails migration works under the hood.