Nested Resource Routing Lab
Objectives
- Write nested routes
- Filter data sets based on nesting
- Handle errors in nested routes
Overview
In this lab, we're going to extend our song library using nested resources to build new routes for our artists and songs, and then 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.
Instructions
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.
Before running the lab, remember to do a 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 in a link to the index of all songs by that artist. - Update the artist
show
view to list each song for that artist and use the new nested resource route helper in a link to view each song. - Update the
songs_controller
to allowindex
andshow
to handle a valid song for the artist. - In the songs
index
action, if theArtist
can't be found, redirect to the artists index 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 the artist's songs index 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 if the result isnil
.
View Objectives on Learn.co and start learning to code for free.