Preloading in Elixir/Ecto

This is a pattern for preloading in Elixir that I have adopted for a few projects. I’m sharing it here for reference. The idea is to have one place to define your preloads instead of in every query.

@preloads [:listens]
defp with_preloads(query), do: preload(query, ^@preloads)
def preload_artist(artist), do: Repo.preload(artist, @preloads)

with_preloads can be used to enhance an query with preloads:

def list_artists do
 Artist
 |> with_preloads()
 |> Repo.all()
 end

Whereas preload_artist() is used to preload a single object, for example, after getting a single artist:

def get_artist!(id), do: Repo.get!(Artist, id) |> preload_artist()