Search code examples
elixirecto

Ecto remove preload


Is there any way to do the inverse to preload?

%Post{
  comments: []
}

posts = Repo.all(Post) |> Repo.unload(:comments)

%Post{
  comments: #Ecto.Association.NotLoaded<association :comments is not loaded>,
}

Solution

  • Ecto.Association.NotLoaded is a plain old simple struct, so you might relatively easy implement this unpreload youself:

    defmodule Unpreloader do
      def forget(struct, field, cardinality \\ :one) do
        %{struct | 
          field => %Ecto.Association.NotLoaded{
            __field__: field,
            __owner__: struct.__struct__,
            __cardinality__: cardinality
          }
        }
      end
    end
    

    And use it later as:

    Unpreloader.forget(%Post{....}, :comments)