Reading
- Read the Rails Guide about Active Record migrations Show archive.org snapshot
- Understand why we never use models in migrations.
- Checkout the repository Project Hero and read through some migrations in
db/migrate. Find two complex migrations and discuss them with your mentor.Tip
Find the largest files in the
db/migratefolder. - Read and understand How to write complex migrations in Rails
Discuss with your mentor
- Instead of migrations, could we simply log into the production server's SQL console and alter tables there whenever we need a change?
- How do we need to work with migrations when we change feature branches?
Exercise
In MovieDB, add two fields:
-
Actor#total_movies: This field should cache the total number of movies an actor stars in -
Actor#first_movie_id: This field should cache the first movie to which the actor starred in. The first movie is the movie with the lowest#created_attimestamp.
Add
callbacks
Show archive.org snapshot
to your ActiveRecord models so the field is always up to date. For the purpose of this exercise, please don't use the :counter_cache option and do everything manually instead.
Whenever you add a new column you need to take care of existing records. Add a migration that sets the total_movies and first_movie_id column for existing records. Write this migration in multiple styles:
- Embedding ActiveRecord models into your migration
- SQL statements (
update "UPDATE actors SET ...")
Posted by Henning Koch to makandra Curriculum (2015-08-20 15:20)