I’m having some issues with association preloading in Ecto.
I have two models,
Post can have many
If I create a post and an image,
Repo.insert(post_with_image) it returns a Post struct with
But if create a
Repo.insert(post_without_image) it returnes
PostView I do
render_many(post.images, ImageView "image.json") which fails when I create a Post without an image.
It is optional for a user of my API to include an image.
How do you typically avoid this?
- Check the value of
post.imagesbefore rendering the images (if it’s an Ecto.AssociationNotLoaded, replace it with a )? Feels a bit weird, because I use the same view to render the show action for instance, and then if I forget to preload the images I won’t notice that (I would in my tests probably but it would just render an empty list and not give me a good error message).
- Preload after insert (seems dumb since it won’t have any images because we just created the post).
- Something else?