0
votes

I have action in user_controller:

defmodule MyAppWeb.Api.V2.UserController do
    use MyAppWeb, :controller
    plug MyAppWeb.Plugs.Auth
    action_fallback MyAppWeb.FallbackController

    def show(conn, _) do
        conn
        |> put_status(:ok)
        |> render(MyAppWeb.Api.V2.UserView, "user.json", user: conn.assigns.current_user)
    end

end

and user_view.ex:

defmodule MyAppWeb.Api.V2.UserView do
    use MyAppWeb, :view
    alias MyAppWeb.Api.V2.UserView
    require Logger

    def render("show.json", %{user: user}) do
        %{data: render_one(user, UserView, "user.json")}
    end

    def render("user.json", %{user: user, session: session}) do
        Logger.warn "here"
        Logger.warn inspect(session)
        %{
            token: session.token,
            credits: MyApp.Account.get_user_balance(user)
        }
    end

    def render("user.json", %{user: user}) do
        %{
            credits: MyApp.Account.get_user_balance(user)
        }
    end

end

The problem is that the result of the query renders render("user.json", %{user: user, session: session}) instead of render("user.json", %{user: user}):

15:06:25.157 request_id=034c7f0sjbglmb0ocl1f1rehe6b0tjrv [warn] here
15:06:25.163 request_id=034c7f0sjbglmb0ocl1f1rehe6b0tjrv [warn] %MyApp.Sessions.Session{...}
15:06:25.176 request_id=034c7f0sjbglmb0ocl1f1rehe6b0tjrv [warn] %{"credits" => %{...}, "token" => "7Zo...Eu"}

why is this happening?

because I do not pass the session to view.

Phoenix version 1.3.0, Elixir version 1.5

1

1 Answers

0
votes

As clearly stated in Phoenix.Controller.render/3 documentation, the assigns from the controller are merged with the connection assigns (conn.assigns):

assigns — a dictionary with the assigns to be used in the view. Those assigns are merged and have higher precedence than the connection assigns (conn.assigns)

To hijack the default behaviour, one might explicitly pass session: nil to render since it has a higher precedence than the connection assigns.