Search code examples
elixirphoenix-frameworkecto

elixir - protocol Enumerable not implemented error when preload with empty roll


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?


Solution

  • 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