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.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. 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 /articles lists, POST /articles creates. 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/new with this table?

    ```text
    1. GET /articles index
    2. GET /articles/{id} show
    3. GET /articles/new new_form
    4. POST /articles create
    `

    • show, with id equal to new
    • new_form, because it is the most specific route
    • index, because /articles is a prefix of the path
    • None: the answer is 404, because new is not a number
    Show the answer

    show, with id equal to new

    {id} accepts any segment, new included, and route 2 is read before route 3. Declare /articles/new before /articles/{id}, or restrict id to 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 receives id = '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/42 and /articles/new, but neither /articles nor /articles/42/comments: a slot only covers a single path segment.

  • The creation form sends POST /articles and gets 405 Method Not Allowed, although GET /articles shows 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 /articles route is only declared for GET
    Show the answer

    The /articles route is only declared for GET

    The path is known, the method is not: that is exactly a 405. A POST /articles route 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.