Ecto preloads not working in query but working in repo

Weird problem, I’m getting a preload fail to load when Query, but succeed with Repo. I’ve never run into this before. Any idea what I’m doing wrong?


defmodule Db.Schema.AccessToken do
  use Ecto.Schema

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  @timestamps_opts [type: :utc_datetime_usec]

  schema "access_tokens" do
    field :name, :string
    field :encrypted_hash, :string
    field :token_representation, :string

    belongs_to :user, Db.Schema.User

    field :expires_at, :utc_datetime


alias Ecto.Query
|> Query.preload(:user)
|> Repo.all() # <== [%AccessToken{user: %EctoAssociationNotLoaded{}...}]
|> Repo.all()
|> Repo.preload(:user) # <== [%AccessToken{user: %User{...}}]

Hi @ityonemo can you show the actual code that is exhibiting the error? Your examples use Repo.all but then your output only shows a single item, leading me to believe that this is not actually the code you’re running.

1 Like

Sorry, that’s a transcription error, it does indeed return lists.

I’ll try spinning up a test repo if my error is not immediately obvious

Not sure it would matter but what does Db.Schema.User look like? I spent about 5 mins trying to reproduce with a similar association and I couldn’t. I have the same primary key and timestamp settings even (not that that should matter).

1 Like

I just made a dummy project and couldn’t myself :sweat_smile:

IIRC then the two preload behaves differently, the former would require a join wheres the latter would join the the result. The latter uses two selects.

Honestly first time seeing somebody having trouble with that. I once pushed successfully for us to introduce a consistent style of preloads – the team was using two – and after voting they settled on your way and they never had an issue.

Has to be some macro / code injection / configuration magic somewhere.