I'm missing something basic with my phoenix code
This is in my controller
def show(conn, %{"id" => id}) do
user = Repo.get!(User, id)
query =
from c in Card,
where: c.user_id == 1,
select: {c.id, c.inserted_at, c.estimate_name, c.product}
estimates = Repo.all(query)
render(conn, "show.json", %{user: user, estimates: estimates})
# render(conn, "show.json", user: user)
end
And in my view
# def render("show.json", %{user: user}) do
def render("show.json", %{user: user, estimates: estimates}) do
%{data: render_one(%{user: user, estimates: estimates}, Api.UserView, "user.json") }
# %{data: render_one(user, Api.UserView, "user.json")}
# ** New code since original post **
# %{data: render("user.json", %{user: user, estimates: estimates})}
end
def render("user.json", %{user: user, estimates: estimates}) do
# def render("user.json", %{user: user}) do
%{id: user.id,
firstname: user.firstname,
lastname: user.lastname,
email: user.email,
customerId: user.customerId,
estimates: render("estimates.json", estimates)} # **Line with last error**
end
def render("estimates.json", [head | _estimates]) do
# Enum.map(estimates, fn estimate -> render(mapper estimate, MosaicApi.UserView, "summaryEstimate.json") } end)
# render(mapper(head), MosaicApi.UserView, "summaryEstimate.json")
render("summaryEstimate.json", mapper(head))
end
# ** I'm fear I have added unnecessary complexity here **
def mapper({id, date, name, product}) do
%{id: id,
creation_date: date,
estimate_name: name,
product: product}
end
def render("summaryEstimate.json", estimate) do
%{id: estimate.id,
estimate_name: estimate.estimate_name,
product: estimate.product}
end
But I get an error, which seems to be because my data has morphed from %{user: ..., estimates: [...]}
to %{user: %{estimates:[...], user: %{...}}
.
How did that happen, and how can I prevent it?
Could not render "user.json" for MosaicApi.UserView, please define a matching clause for render/2 or define a template at "web/templates/user". No templates were compiled for this module.
Assigns:
%{user: %{estimates: [{1, #Ecto.DateTime<2016-04-26T12:01:34Z>, "cards for annabelle", "Business Cards"}, ...], user: %Api.User{__meta__: #Ecto.Schema.Metadata<:loaded>, customerId: "CUST", email: "foo@foo.be", firstname: "fname 1", id: 1, inserted_at: #Ecto.DateTime<2016-04-26T11:46:21Z>, jobs: #Ecto.Association.NotLoaded<association :jobs is not loaded>, lastname: "lname 1", updated_at: #Ecto.DateTime<2016-04-26T11:46:21Z>}}, view_module: Api.UserView, view_template: "user.json"}