我在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
和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
问题是查询结果呈现render("user.json", %{user: user, session: session})
而不是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"}
为什么会这样?
因为我没有通过会议来查看。
Phoenix版本1.3.0,Elixir版本1.5
答案 0 :(得分:0)
如Phoenix.Controller.render/3
文档中所述,控制器中的assigns
与连接分配(conn.assigns
)合并:
•
assigns
- 包含要在视图中使用的分配的字典。这些分配是合并的,其优先级高于连接分配(conn.assigns
)
要劫持默认行为,可能会明确地将session: nil
传递给render
,因为它的优先级高于连接分配的优先级。