What function can I use to check if a association is already loaded?
It would be nice to check if a association is loaded instead of trying to use it and getting Ecto.Association.NotLoaded
error.
You can use assoc_loaded?
Reference: https://hexdocs.pm/ecto/Ecto.html#assoc_loaded?/1
Not sure if there's a built-in function to check for this, but you could write your own like this:
defmodule PreloadCheck do
def is_preloaded(model, assoc) do
case Map.get(model, assoc) do
%Ecto.Association.NotLoaded{} -> false
_ -> true
end
end
end
Here assoc
would be the atom representing your association name.
Using pattern matching in case
allows you to check if your association is loaded or if it's still returning a Ecto.Association.NotLoaded
struct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With