Generate virtual field for Ecto relationship

I think this is roughly the same question as What's the easiest way to populate ecto's virtual field with database data unless I’m misunderstanding. In that case, sorry to be a broken record, but I’d still say query and then decorate the records. One way with a relationship would be something like…

artist = Repo.get(from(Artist, preload: :tracks), artist_id)
tracks = Enum.map(artist.tracks, &with_poster_url/1)
artist = Map.put(artist, :tracks, tracks)

Depending upon what you’re doing, you might want to just query for the tracks separately and then decorate. This would be no different than preloading since both involve two queries. It’s just that preload will automatically add the tracks to the artist struct.

1 Like