You’re setting up the routes for a website that displays information on different genres of music. Using the URL path /music/
as an example, create a route that uses a single controller action for each genre of music with the actual music genre passed into the controller action as a parameter. The valid music genres are as follows: classical, rock, house, country, hip_hop, and rnb. All other genres should generate a 404 status code.
You will likely receive a variety of potential answers for an open-ended coding question like this, but here are two of the most straightforward approaches to creating a route. The most straightforward solution would be to create a simple route that specifies the controller action to call and passes the genre of music as a parameter. If the genre parameter is not included in the list of valid genres, the action will raise an ActionController::RoutingError
and redirect to a 404 page.
get 'music/:genre' => 'music#genre'
Alternatively, a better solution would be to use resource routing which comes with the added benefit of URL generation helpers. You can use the constraints option to verify the validity of a route by checking the parameter against a list of genres. This method requires that the parameter name for the genre be passed as :id
and would look something like this:
genres = %w|classical rock house country hip_hop rnb|
resource :music, only: [:show], constraints: {id: Regexp.new(genres.join('|'))}