Routes and controllers
The route table, path and query parameters, the order of routes, 404 and 405 responses, and the job of a controller: read the request, call the model, choose the response.
- 23 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Route: what is it?
Show the answer
A rule that ties an HTTP method and a URL pattern to the action in charge of handling the request.
One path can carry several routes depending on the method:
GET /articleslists,POST /articlescreates. All the routes together form the table the application scans on every request.The router keeps the first route that matches. Which action handles
GET /articles/newwith this table?
```text
1. GET /articles index
2. GET /articles/{id} show
3. GET /articles/new new_form
4. POST /articles create`show, withidequal tonewnew_form, because it is the most specific routeindex, because/articlesis a prefix of the path- None: the answer is 404, because
newis not a number
Show the answer
show, withidequal tonew{id}accepts any segment,newincluded, and route 2 is read before route 3. Declare/articles/newbefore/articles/{id}, or restrictidto digits.In the pattern
/articles/{id},{id}is a …: the application extracts its value from the URL and passes it to the action.Show the answer
In the pattern
/articles/{id},{id}is a path parameter: the application extracts its value from the URL and passes it to the action.For
GET /articles/42, the action receivesid = '42', as text by default: converting it to an integer is still up to you, unless the route enforces a type.URL pattern: what is it?
Show the answer
A path template containing variable slots between braces, which the application compares with the URL received.
/articles/{id}accepts/articles/42and/articles/new, but neither/articlesnor/articles/42/comments: a slot only covers a single path segment.The creation form sends
POST /articlesand gets405 Method Not Allowed, althoughGET /articlesshows the list fine. What is the cause?- The form is filled in wrongly and the server rejects it
- The create action crashes and the application returns 405 by default
- The user is not logged in, so the method is forbidden
- The
/articlesroute is only declared forGET
Show the answer
The
/articlesroute is only declared forGETThe path is known, the method is not: that is exactly a 405. A
POST /articlesroute to the create action is missing. A crash would give 500, rejected input a 400 or 422, a missing session a 401 or a redirect to the login page.