I'm using Phoenix 1.3.0-rc
and I would like to print a url in my json return using user_path(...)
.
My controller:
...
def show(conn, %{"id" => id}) do
user = User.find(id)
render(conn, "show.json", user: user)
end
...
My view:
...
def render("show.json", %{user: user}) do
%{
data: render_one(user, __MODULE__, "user.json"),
links: render_one(user, __MODULE__, "links.json")
}
end
...
def render("links.json", %{user: user}) do
%{
self: "/api/v1/users/#{user.id}"
}
end
...
I would like to write this:
self: user_path(conn, :show, user.id)
But I get this error: undefined function conn/0
You have to pass conn through to the view. Note that Phoenix.Controller.render/3
is not the same as Phoenix.View.render/3
. "The former expects
a connection and relies on content negotiation while the latter is
connection-agnostic and typically invoked from your views".1
In your controller:
def show(conn, %{"id" => id}) do
user = User.find(id)
render(conn, "show.json", user: user, conn: conn)
end
And your view:
def render("show.json", %{user: user, conn: conn}) do
%{
data: render_one(user, __MODULE__, "user.json"),
links: render_one(user, __MODULE__, "links.json", conn: conn)
}
end
...
def render("links.json", %{user: user, conn: conn}) do
%{
self: user_path(conn, :show, user.id)
}
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With