In this drill, we're going to explore migration hell. Please come along.
The #1 rule of migration hell is this:
Got it?
Cool.
Let's begin
-
Create a new rails app. Make sure to use postgres. You got this one.
-
Add some models
> rails g model recipe name:string instructions:string posted:string
> rails g model ingredient name:string amount:string
- Create a relationship between these models using the has_and_belongs_to_many shorthand.
> rails g migration create_join_table_ingredients_recipes ingredients recipes
-
Migrate!
-
Add the relationship in your models:
# models/ingredient.rb
class Ingredient < ActiveRecord::Base
has_and_belongs_to_many :recipes
end
# models/recipe.rb
class Recipe < ActiveRecord::Base
has_and_belongs_to_many :ingredients
end
- Test out these associations in the rails console.
-
Oops! I forgot that I wanted an
author
attribute on therecipe
model. Add this attribute now keeping in mind the #1 rule of migration hell. -
Now that I'm thinking about it, I actually don't want that
author
attribute... Sorry. Can you delete this attribute? -
This is really weird. I really didn't think this was going to happen, but I was thinking... shouldn't
instructions
actually be calledsteps
? Yeah. That makes more sense to me. Modify this attribute. -
I just realized that I accidentally made the
posted
attribute on recipes a string! This should be a datetime, der. Can you help me out to change this datatype? -
I want a new table. Let's call it
comments
and make it a 1:n relationship withrecipes
. K thanks. -
Blerg I HATE comments. Comments are sooo 2015. Drop that table.