defmodule Admin.UserView do
use AdminWeb, :view
def render("show.json", %{user: user}) do
%{
data: render_one(user, Admin.UserView, "user.json")
}
end
def render("user.json", %{user: user}) do
%{
id: user.id,
name: user.name,
}
end
end
I am calling it like this
render(conn, "show.json", user: user)
It throws 500 error when i try to test it. But it works fine if I modify the code like this
def render("show.json", %{user: user}) do
%{
data: %{
id: user.id,
name: user.name,
}
}
end
I don’t see any thing wrong with user.json render function.
Any idea why it throws an error? May be I am missing something
defmodule Admin.UserView do
use AdminWeb, :view
def render("show.json", %{user: user}) do
%{
data: render_one(user, __MODULE__, "user.json", as: :user)
}
end
def render("user.json", %{user: user}) do
%{
id: user.id,
name: user.name,
}
end
end
And in controller render(conn, Admin.UserView, "show.json", %{user: user})
IMO this should help you - render should be as render/4 with conn, view, action, parameters details.
def render("show.json", %{user: user} = assigns) do
%{
data: render_one(user, Admin.UserView, "user.json", assigns)
}
end
There’s no “implicit” assigns map, which all functions would automatically inherit somehow. You need to explicitly pass the assigns map onwards into render_one.