Skip to content

Instantly share code, notes, and snippets.

@aschiavon91
Last active June 16, 2025 12:30
Show Gist options
  • Select an option

  • Save aschiavon91/aa23eaf3267274c9773bef0cc5249f8f to your computer and use it in GitHub Desktop.

Select an option

Save aschiavon91/aa23eaf3267274c9773bef0cc5249f8f to your computer and use it in GitHub Desktop.
[Elixir][Ecto][Phoenix] A simple way to unload preloaded association of an ecto record struct.
defmodule MyApp.Repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: Ecto.Adapters.Postgres
def unload(_, _, cardinality \\ :one)
def unload(struct, fields, cardinality) when is_list(fields) do
Enum.reduce(fields, struct, fn field, struct_acc ->
unload(struct_acc, field, cardinality)
end)
end
def unload(struct, field, cardinality) when is_atom(field) do
%{
struct
| field => %Ecto.Association.NotLoaded{
__field__: field,
__owner__: struct.__struct__,
__cardinality__: cardinality
}
}
end
def unload(struct, field, _) do
raise "Error: #{field} is not a valid field to #{struct.__struct__}"
end
end
@karolsluszniak
Copy link
Copy Markdown

karolsluszniak commented Jun 16, 2025

👍

This can be done to drop the need for cardinality arg:

  def unload(struct, field) do
    owner = struct.__struct__
    assoc = owner.__schema__(:association, field)

    not_loaded = %Ecto.Association.NotLoaded{
      __field__: field,
      __owner__: owner,
      __cardinality__: assoc.cardinality
    }

    Map.put(struct, field, not_loaded)
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment