Preloading has_many relations on creation

I have a resource Lot with a has_many relationship to another resource Item (with a corresponding belongs_to relationship to Lots). The public interface of the context to which they belong only exposes lots, so there are list_lots and get_lot! etc. functions, but no list_items etc. functions. I appear to have preloading of the Items working for list_lots, get_lot!, and update_lot, but create_lot, which looks like this:

  def create_lot(attrs \\ %{}) do
    %Lot{}
    |> Lot.changeset(attrs)
    |> Ecto.Changeset.cast_assoc(:items, with: &Item.changeset/2)
    |> Repo.insert()
  end

gives me a Lot changeset with the items field containing #Ecto.Association.NotLoaded<association :items is not loaded>

I have gone back over the Phoenix Guide, and it does not appear to cover this case. If no associations exist, then I would expect this field on the changeset to be the empty list, which is the case for the working functions mentioned earlier.

How do I load the associations for the %Lot struct this function creates?

try something tlike this https://thoughtbot.com/blog/preloading-nested-associations-with-ecto

Also I have this in my github a simple exmaple of posts relationship with categories.

Simply put, you receive only the inserted record after the operation has completed. Inspect your DB and you will see that the associated records have been inserted as well.

If you like to also return them on creation then just add |> Repo.preload(:items) at the end of your pipe (after |> Repo.insert()).

1 Like

That talks about preloads with queries, but I think I need to be working with the Repo module.

Thanks, that was what I needed to do. I had tried this, but I was misunderstanding the test failures when I made this change without handling the case where Repo.insert returns {:error, %Lot}.