IO.puts(inspect( contacts )) gives:
[%HelloTable.Contact{__meta__: #Ecto.Schema.Metadata<:loaded>,
id: 37,
inserted_at: #Ecto.DateTime<2015-10-22T12:50:43Z>,
name: "Gumbo", phone: "(801) 555-55555",
updated_at: #Ecto.DateTime<2015-10-22T12:50:43Z>}]
And the view looks like:
defmodule HelloTable.ContactView do
use HelloTable.Web, :view
def render("index.json", %{contacts: contacts}) do
IO.puts(inspect( contacts ))
contacts
end
end
As soon as I try to render this view I get:
** (Poison.EncodeError) unable to encode value: {nil, "contacts"}
You will need to either implement the Poison.Encoder
protocol for HelloTable.Contact
as described in Encoding a Ecto Model to JSON in elixir or return a map from the render function using render_many/4:
defmodule HelloTable.ContactView do
use HelloTable.Web, :view
def render("index.json", %{contacts: contacts}) do
render_many(contacts, __MODULE__, "contact.json")
end
def render("contact.json", %{contact: contact}) do
%{
id: contact.id,
name: contact.name,
phone_number: contact.phone
}
end
end
The above is how JSON is handled with in the Phoenix JSON generators.