Now it's time to make a 3-model app! And you guessed it, we'll be introducing a many to
many relationship (n:n
). So what's the deal? Well, it's time to build a cocktail
manager. We want to store our favourite cocktails, and their recipes.
- A cocktail has a name (e.g.
"Mint Julep"
,"Whiskey Sour"
,"Mojito"
) - An ingredient has a name (e.g.
"lemon"
,"ice"
,"mint leaves"
) - A dose is the amount needed for each ingredient in a cocktail (e.g. the Mojito cocktail needs 6cl of lemon). So each dose references a cocktail, an ingredient and has a description.
- A cocktail must have a unique name.
- An ingredient must have a unique name.
- A dose must have a description, a cocktail and an ingredient, and [cocktail, ingredient] pairings should be unique.
- A cocktail has many doses
- A cocktail has many ingredients through doses
- An ingredient has many doses
- A dose belongs to an ingredient
- A dose belongs to a cocktail
- You can't delete an ingredient if it used by at least one cocktail.
- When you delete a cocktail, you should delete associated doses (but not the ingredients as they can be linked to other cocktails).
Our app will not allow users to create ingredients. Instead, we will generate a static seed of ingredients to choose from. Write this seed, for example
# db/seeds.rb
Ingredient.create(name: "lemon")
Ingredient.create(name: "ice")
Ingredient.create(name: "mint leaves")
Once again, you must have a precise idea of the features of your app in order to build your routes. Here is the list of features:
- A user can see the list of cocktails
GET "cocktails"
- A user can see the details of a given cocktail, with the dose needed for each ingredient
GET "cocktails/42"
- A user can create a new cocktail
GET "cocktails/new"
POST "cocktails"
- A user can add a new dose (ingredient/description pair) to an existing cocktail
GET "cocktails/42/doses/new"
POST "cocktails/42/doses"
- A user can delete a dose that belongs to an existing cocktail. How can we make a delete link again?
DELETE "doses/25"
Do we need an IngredientsController
?
Here are some great examples.
Try to put the "New dose form" on the cocktail page, not on a separate page. What changes in the routes? And in the controllers?