Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a association is not loaded?

Tags:

ecto

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.

like image 250
Teo Choong Ping Avatar asked Jun 27 '16 06:06

Teo Choong Ping


2 Answers

You can use assoc_loaded?

Reference: https://hexdocs.pm/ecto/Ecto.html#assoc_loaded?/1

like image 190
marpo60 Avatar answered Oct 02 '22 19:10

marpo60


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.

like image 32
naserca Avatar answered Oct 02 '22 20:10

naserca