0
votes

I have this code:

q = from p in Case, where: p.user_id == ^user_id:
Repo.all(q)
|> Repo.preload(:helper)

with the view render function:

alias ChatWeb.HelperView

def render("api_case.json", %{case: case, message: message, token: token}) do
%{
status: "1",
token: token.token,
items: case.items,
helpers: render_many(case.helper, HelperView, "helper.json"),
}
end

if I have helper data, everything will be OK.

but if I don't have anything in helper, I will get:

protocol Enumerable not implemented for #Ecto.Association.NotLoaded of type Ecto.Association.NotLoaded (a struct)

How can I resolve this?

1
why just not render_many(case, ...) instead of render_many(case.helper, ...), it's easier to handle if there is no data in association, maybe? - copser
It looks like the helper association (why isn't this called helpers?) is not preloaded. Are you sure you're posting/using the correct query? - zwippie

1 Answers

1
votes

It’s not quite clear what do you mean “if I don’t have anything in helper,” but the following would likely do:

def render("api_case.json", %{case: case, message: message, token: token}) do
  helpers =
    case case.helper do
      %Ecto.Association.NotLoaded{} -> []
      many -> render_many(many, HelperView, "helper.json")
    end
  %{status: "1", token: token.token, items: case.items, helpers: helpers}
end