1
votes

I'm running into this error when I'm trying to create a session with a user from the database. My user schema has_many projects So when I try to create the session I get this error

projects: #Ecto.Association.NotLoaded<association :projects is not loaded>

I think I understand what it is saying but I don't know where to preload the data so that the page will render here is the full error that I receive.

defmodule PerriAir.Router do
 use PerriAir.Web, :router
 use Honeybadger.Plug
 use ExAdmin.Route    

 pipeline :browser do



protocol Enumerable not implemented for %PerriAir.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, id: 8, inserted_at: #Ecto.DateTime<2016-12-23 15:38:38>, password: nil, password_hash: "$2b$12$NxLaK3ZUVPLE23E1L.64GOjm7FtTLemXPUXsp6gSAP346is8e6d5e", projects: #Ecto.Association.NotLoaded<association :projects is not loaded>, updated_at: #Ecto.DateTime<2016-12-23 15:38:38>}

I'm new to elixir and phoenix so any help with this error would be appreciated!

1

1 Answers

5
votes

Where you're fetching user, you need to explicitly preload associated :projects, so in controller you have presumably something like:

user = Repo.get(User, user_id)

This has to be turned to something like:

user =
  User
  |> Repo.get(user_id)
  |> Repo.preload(:projects)

Please note, the code is formatted and pipe operator is used here for clarity. Equivalent of it would be something like:

user = Repo.preload(Repo.get(User, user_id), :projects)

I've added that here because you've mentioned you're new to elixir.

If you want to read more about Ecto's preload, take a look here: https://hexdocs.pm/ecto/Ecto.Repo.html#c:preload/3

Hope that helps!