Where the :id in a route comes from?

Hi all,

I am following along the excellent Phoenix in Action book from @geo. In page 59, while he takes us through the life cycle of a request through Phoenix, he says:

from our list of routes, /posts/:id is the path that gets you to this function. The “:id” portion of that route specifies that whatever you put into that position will be passed as the id in the params map.

But when I look at scopes in the router.ex (or the endpoint.ex file before that), I do not see the :id portion anywhere.

defmodule BlogWeb.Router do
  # ...
  scope "/", BlogWeb do
    pipe_through :browser

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

  scope "/api", BlogWeb.API do
    pipe_through :api

    resources "/posts", PostController, only: [:index, :show]
  end
end

Is it supposed to be implied anywhere? How about if I do not what the id but another parameter. Or am I not understanding the philosophy of it?

Thanks very much!

https://hexdocs.pm/phoenix/Phoenix.Router.html#resources/4

Your id will come from the database using a function like this in a context

ex:

def get_customer(id) do
   Customer
   |> Repo.get(id)
end

Then this function will be called in a controller.

To u8nderstand this better follow the phoenix guide here https://hexdocs.pm/phoenix/overview.html

ohhh… right, reading the documentation helps. Sorry about that. So, for what I understand if I want to use another parameter what I need is to define a helper. Let’s say I have a table like this:

id      product_code
1      1001
2      1002
3      4569

and I want to be able to filter by product_code, then I would need something like this?

get "/api/:product_code", ApiController, :show

I understand it wil automatically generate this:

MyAppWeb.Router.Helpers.api_path(conn_or_endpoint, :show, "hello", some: "query")
"/api/hello?some=query"

Am I correct?

Thanks!

OK, that helps. Thank you! I do not see any of that in the provided code but as @LostKobrakai points out, it seems to be implicit. I will read the whole thing carefully to better understand the concept. Thanks again for replying.

To be able to access the resources route you need to have:

  • a migration
  • a schema
  • a controller
  • a view
  • a template.

So you use a mix generator to do that for you but those things need to exist to be able to use the resource route.

The following command might be useful if You want to inspect your routes.

$ mix phx.routes