Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Routing, Controllers and Plugs

Resources, Verified Routes and Nested Routes

Use the resources macro for RESTful routes, generate safe links with ~p verified routes, nest resources, restrict actions and build URLs in controllers and tests.

Most web apps repeat the same seven operations for every kind of thing: list, show, new form, create, edit form, update and delete. Phoenix packages these as resources. The resources macro generates all seven routes in the right order, and verified routes (~p) let you link to them with the compiler checking every path.

In this lesson you will use resources with options, nest resources, and generate links that Phoenix verifies at compile time. You need the router basics and controller actions.

The seven RESTful routes

ELIXIR
resources "/posts", PostController

expands to:

Verb Path Action Purpose
GET /posts :index List all posts
GET /posts/new :new Form for a new post
POST /posts :create Save a new post
GET /posts/:id :show Show one post
GET /posts/:id/edit :edit Form to edit
PATCH / PUT /posts/:id :update Save changes
DELETE /posts/:id :delete Remove a post

Note that /posts/new is defined before /posts/:id, which avoids the matching bug from the router lesson. Controller actions are expected to have exactly these names.

Restrict the set with only or except:

ELIXIR
resources "/posts", PostController, only: [:index, :show]
resources "/sessions", SessionController, only: [:new, :create, :delete], singleton: true
resources "/comments", CommentController, except: [:delete]

singleton: true is for a resource with one instance per user (like a profile): no :id in the path.

Nested resources

A comment belongs to a post, so its URL should say so:

ELIXIR
resources "/posts", PostController do
  resources "/comments", CommentController, only: [:index, :create, :delete]
end

This creates /posts/:post_id/comments and /posts/:post_id/comments/:id. The parent id arrives as post_id in params. Do not nest more than one level deep: /posts/1/comments/2/likes/3 is awkward. Once a child has its own id, give it a top-level route as well.

Verified routes with ~p

Hard-coded paths in templates break silently when a route changes. Phoenix's verified routes use the ~p sigil, and the compiler warns if the path does not match any route in the router:

ELIXIR
~p"/posts"                 # "/posts"
~p"/posts/#{post}"         # "/posts/42" (uses Phoenix.Param, by default the id)
~p"/posts/#{post}/edit"
~p"/posts?page=2"
~p"/posts?#{%{page: 2, sort: "title"}}"   # "/posts?page=2&sort=title"

Interpolating a struct calls Phoenix.Param.to_param/1, which returns the id by default. To use a slug instead, derive the protocol on the schema:

ELIXIR
@derive {Phoenix.Param, key: :slug}
schema "posts" do
  field :slug, :string
  ...
end

Then ~p"/posts/#{post}" produces /posts/hello-world.

Use ~p in controllers (redirect(conn, to: ~p"/posts")), templates (<.link navigate={~p"/posts"}>), tests and everywhere else. If you rename a route and forget a link, mix compile prints a warning like no route path for BlogWeb.Router matches "/post".

For full URLs including host (emails, API responses), use url(~p"/posts/#{post}") which prefixes the endpoint's configured URL.

mix phx.routes lists everything the macro created. For resources "/posts" and the nested comments you will see 7 plus 3 routes, each with its action. Use it after every router change.

Resources versus plain routes

Do not force everything into REST. A search page, a webhook endpoint or a dashboard is clearer as a plain get or post. Use resources where your data is a collection of things with standard operations, and plain routes elsewhere:

ELIXIR
get "/search", SearchController, :index
post "/webhooks/stripe", WebhookController, :stripe

Expanding resources, modeled

JS What resources generates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output shows /posts/:post_id/comments for the nested pair: the parent id is named after the parent resource.

Verified routes, modeled

JS A tiny ~p that rejects unknown paths

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second call warns. Phoenix does this at compile time rather than at run time, so mistakes never reach production.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many routes does a plain resources "/posts", PostController create (counting PUT and PATCH as one)?

    index, new, create, show, edit, update and delete. update is reachable by both PATCH and PUT.
  2. 2. What does ~p"/posts/#{post}" do with a struct?

    The Phoenix.Param protocol turns the struct into a path segment; derive it to use a slug.
  3. 3. What does verified routes catch?

    The compiler warns when a ~p path cannot match any route in the router.
  4. 4. Which option removes the id from a resource's paths?

    A singleton resource has one instance per user or session, so its paths carry no id.

Summary

  • resources generates the seven RESTful routes in a safe order; restrict them with only, except or singleton: true.
  • Nest resources one level deep; the parent id appears as post_id.
  • Use ~p everywhere for compile-time checked paths; interpolated structs use Phoenix.Param.
  • Use plain get/post routes for things that are not CRUD.

Next: JSON APIs and fallback controllers