Phoenix Router: Generating a path from a controller and action, not a named route?

Is there a way of generating a path from the current controller, an action and any route parameters, without using a named route helper?

My use case is that I’m implementing a single controller on multiple paths, by passing in an assign opt which changes the behaviour. I want index in the controller to redirect to show, without hardcoding the route, which will differ depending on the path the user is accessing the controller through.

For example:

get "/foo", MyController, :show, assigns: %{mode: App.Modes.Foo}
get "/foo/:id", MyController, :index, assigns: %{mode: App.Modes.Foo}

get "/bar", MyController, :show, assigns: %{mode: App.Modes.Bar}
get "/bar/:id", MyController, :index, assigns: %{mode: App.Modes.Bar}
defmodule AppWeb.MyController do
  use AppWeb, :controller

  def index(conn, _params) do
    |> redirect(to: path_to_show_action)

apply(Routes, name, args) is likely the simplest option.

1 Like

Thanks - I was hoping to avoid doing some magic to convert the camel case MyController to my_path, but if that’s the only way, that’d work!

I suppose I could also pass it in explicitly through assigns.

Phoenix.Naming includes the underscore function if you are trying to avoid extra dependencies.

1 Like