We are going to continue our todoapp by adding 2 models, Task and Comment. We will use generators (scaffolds) for both models. The Task will have many Comments and a Comment will belong to a Task. As a bonus, lets use a nested route.
To begin, let’s generate our full Task scaffold.
mix phoenix.gen.html Task tasks name:string body:text
The instructions following this command are important. Ensure you add the code
resources '/tasks', TasksController
Then lets add the table to our database.
To see all that
mix offers, use this
1 2 3 4 5 6 7 8 9
The Comment generator is just as easy.
mix phoenix.gen.html Comment comments body:text task_id:integer
Again, we need to follow the instructions after this generator.
Now lets open
web/router.ex and make our nested routes.
1 2 3
After this change, we will want to search the project and repair any URL helpers that no longer make sense.
mix phoenix.routes will show you what routes are available.
comments_path is now
task_comments_path and so forth. This is a bit tedious and can be avoided by creating the generator files manually.
We can now open each model and associate them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Now to use this relation in a view, for example
1 2 3
We will need to preload the association. To do this, we can prepare the data in the controller
And the associations now work with the view!