Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using conn on view to render url

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

like image 613
Lucas Franco Avatar asked Mar 09 '23 19:03

Lucas Franco


1 Answers

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
  1. https://github.com/phoenixframework/phoenix/blob/master/lib/phoenix/controller.ex#L156
like image 122
Jack Noble Avatar answered Apr 08 '23 03:04

Jack Noble