Hello
In the router.ex
file, I have the following route:
resources "/users", UserController
In a Controller, I can use the route path helper:
redirect(to: Routes.user_path(conn, :show, user))
Why does it work? user
is a struct, but the path/url will contain an id.
In the examples, primitives are passed, e.g.
HelloWeb.Router.Helpers.user_post_path(Endpoint, :show, 42, 17)
So that doesn’t explain why structs can be passed.
They are functions that accepts structs and converts them
Scroll down to helpers comment and examine the functions you will see conn structs and endpoints structs
3 Likes
In particular…
defp to_param(int) when is_integer(int), do: Integer.to_string(int)
defp to_param(bin) when is_binary(bin), do: bin
defp to_param(false), do: "false"
defp to_param(true), do: "true"
defp to_param(data), do: Phoenix.Param.to_param(data)
With pattern matching (and guards) it is simple to extract id from struct, or any…
3 Likes
Thank you! This is where the code tries to find the value from the struct:
1 Like
You are welcome, glad I could help