Last active
June 16, 2025 12:30
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍
This can be done to drop the need for cardinality arg: