Views not working in json api

I have this view file .

 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

Thanks

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.

1 Like

Hi thanks for your reply.
But in phoenix documentation render/3 is working fine.

   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.

1 Like