This sounds like the same kind of issue I answered in another post recently. Ecto `change/2` preloading associations? - #3 by 03juan
Basically when you build a new struct, the change function replaces NotLoaded
with the respective “empty” value, nil
for belongs_to
and has_one
or []
for has_many
, specifically for things like forms so you don’t have to do it manually. But when you’re loading an existing record from the db you have to preload the association to replace the NotLoaded
struct before you access the data.
Since you mention Jason I assume you’re setting up your own api controller. If you want to send the base struct without having to preload, the you can either @derive {Jason.Encoder, except: [:user, :breed]}
above the schema "pets"
declaration, which will always strip out those keys when serialising, or manually define your own protocol implementation so you can send the nested user and breed when they’re preloaded or exclude those keys when their values are NotLoaded
.
See the defimpl Jason.Encoder
example and let us know how it goes.