Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JSON only Phoenix view
defmodule MyApp.UserController do
use Phoenix.Controller
def show(conn, %{"id" => id}) do
render conn, "show", user: Repo.get!(user, id)
end
def index(conn, _) do
render conn, "index", users: Repo.all(User)
end
end
defmodule MyApp.UserView do
use MyApp.View
def render("show.json", %{user: user}) do
user |> to_map
end
def render("index.json", %{users: users}) do
users |> Enum.map(&to_map(&1))
end
defp to_map(user = %User{}) do
%{
id: user.id,
name: user.name,
age: user.age
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment