One of the things that AR had from Day1 (Rails 1.2 at least) is something called Migrations.
In apps with dbs, every dev has their own copy of the db.
New features and updates to (web) apps that uses DBs may require not only code changes but also database structural/schema changes.
If you make those changes manually using a SQL tool or editor. Of course you then modify the code so it uses the new schema and implements the new feature.
You push the code to github.
What happens next?
Some other developer pulls master and has the new code. But it doesn't have any record of the DB changes.
Now the second developer has to rerun the same SQL schema changes on their local db. WTF
Make database changes incrementally via migrations which are part of the source code (ruby / activerecord code).
Migrations are ruby files that are not run by your app, but rather by developers one time to make those one times structural changes to their db.
- Dev A creates a new migration file with the
create_table
and other changes - Dev A runs the migration against their own local db (
rake db:migrate
) - Dev A makes the appropriate code changes
- Dev A is done with the feature change and pushes the code + new migration file
- Dev B pulls
- Dev B notices new migration files in the pull
- Dev B runs
rake db:migrate
same as Dev A did - Dev B's rake command notices the new migration file and runs the
create_table
on her db - Dev B's code and db are now same as Dev A's
Once a migration runs, it is not going to run again on the same db. Unless of course you drop and recreate the db (rake db:drop
and rake db:create
) first.
We discovered that AR remembers this via a table called schema_migrations
that it inserts into every time it runs a migration succesfully. This table keeps track of the ID's of the migrations that have already been run. It determines that there is a migration that HASN'T been run yet by finding a filename that begins with an ID that is greater than the last migration that was recorded. This is why we name migration files using the date format YYYYMMDDHHMMSS_create_teachers.rb. This ensures that the ID (the date) is always increasing in value as we add migrations.
The up
method is what's executed in a migrate. The down
method (not used today) is what's executed in a rollback
.
There's a change
method that is newer and for simpler migrations so you don't have to manually write a down. Fancier / more magic for certain situations.