Can we preload a preloaded association?

I have Users that has many Photos and the Photos have a Location.

user = Repo.get_by(User, id: id)
result = user |> Repo.preload([:photos])

Up to here works fine but when I try to preload Location, ecto looks inside User to preload, not Photos.

I haven’t tried that, but in queries you can do it:

Repo.all from p in Post, preload: [comments: :likes]

so it seems to me it should be possible to do:

result = user |> Repo.preload([photos: :location])

but I haven’t actually tested if that works.

1 Like

Yes, it should work. :smiley:

here’s one for the API consistency! :tropical_drink:

hm… I already tried that though.

result = user |> Repo.preload([:photos])
cannot encode association :location from Foodhunt.Photo to JSON because the association was not loaded. Please make sure you have preloaded the association or remove it from the data to be encoded

result = user |> Repo.preload([:photos, :location])
schema Foodhunt.User does not have association :location

Repo.all(Photo) |> Repo.preload([:location])

This works so it’s not a problem with the schema.

[:photos, :location] != [photos: :location]

3 Likes

I should read more carefully XD. I appreciate the help! Thanks guys.

It’s still pretty minimalistic but here’s the code in action! https://foodhunt.org/CH/map