- Write nested routes
- Filter data sets based on nesting
- Handle errors in nested routes
In this lab, we're going to extend our song library using nested resources to build new routes for our artists and songs. Then, we'll use the URL helpers in our views to expose these new routes.
We'll also be handling errors when nested resources aren't found so that we can provide a more professional experience to our users.
The base models, controllers, views, and other files have been provided. There are tests for the lab in the spec
directory. You can run tests with the rspec
command.
Remember to rake db:seed
to set up a starter song library!
- Create nested resource routes to show all songs for an artist (
/artists/1/songs
) and individual songs for that artist (/artists/1/songs/1
). Restrict the nested songs routes toindex
andshow
actions only. - Update the artists
index
view to use the new nested resource route URL helper to link to the index of all songs by that artist. - Update the artists
show
view to list each song for that artist, and use the new nested resource route helper to link each song to its correspondingshow
page. - Update the
songs_controller
to allow thesongs#index
andsongs#show
actions to handle a valid song for the artist. - In the
songs#index
action, if the artist can't be found, redirect to theindex
of artists, and set aflash[:alert]
of "Artist not found." - In the
songs#show
action, if the song can't be found for a given artist, redirect to theindex
of the artist's songs and set aflash[:alert]
of "Song not found." - Make sure all tests pass; then, party down!
Hints
- For a refresher on the use of
flash
, see the ActionController RailsGuide. - Remember when filtering nested resources to query for the children through the parent, e.g.,
@artist.songs.find_by(id: ...)
- There's more than one way to ride the Rails. You could handle not being able to find a record by using
rescue ActiveRecord::RecordNotFound
, or you could try usingfind_by(id: id)
instead offind()
and checking to see whether the result isnil
.