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

Hi,
I’m trying to automatically get the other table(wallet) to preload in my table(device) without declaring everytime through terminal.
When I run this command [device1, device2] = Devices.list_devices([limit: 2]). Get this response:

But when I run this command with calling preload inside command then I get the wallet table details too: [device1, device2] = Devices.list_devices([limit: 2]) |> Repo.preload(:wallet).
Screen Shot 2022-10-07 at 1.51.05 AM

However in my code, I’ve initialized it inside list_devices to load the wallet too. But not working.

def list_devices(criteria) do
    query = from d in Device

    Enum.reduce(criteria, query, fn
      {:limit, limit}, query ->
        from d in query, limit: ^limit

      end)
      |> IO.inspect()
      |> Repo.all
      |> Repo.preload(:wallet)
  end

Seeking help! Thanks

You might do it like this…

def list_devices(criteria) do
    query = from d in Device

    Enum.reduce(criteria, query, fn
      {:limit, limit}, query ->
        from d in query, limit: ^limit
      {:preload, preload}, query ->
        from d in query, preload: ^preload
      end)
      |> IO.inspect()
      |> Repo.all
  end

Then You could do…

Devices.list_devices(limit: 2, preload: :wallet)

It’s easy to extend (offset, order, order_by)
But I prefer to separate…

def list_devices_query(criteria) do
...
end
def list_devices(criteria) do
  criteria
  |> list_devices_query()
  |> Repo.all()
end

… because sometime it’s useful to have access to queries

1 Like

But still getting this.
I actually don’t want to call wallet by myself in terminal. I want it to load automatically.
But I tried this way and still its not loading.
Screen Shot 2022-10-07 at 2.09.47 AM

You can do your own list…

def my_list_devices, do: list_devices([limit: 2, ...])

That is how I wrap my generic functions with a preset of parameters

1 Like