Generate virtual field for Ecto relationship

I fill the virtual fields recursively after fetching data, e.g.

User
|> # some Ecto query with dynamic preloads
|> # Repo call
|> fill_virtual_fields()

And the fill_virtual_fields/1 function will fill the virtual fields for the entity and all the nested entities; this allows the Context not having to care about which field is virtual or not, and how to fill it. fill_virtual_fields/1 will call an implemented behaviour on all entities that have a need to fill virtual fields.

I made a small lib out of it: GitHub - mathieuprog/virtual_fields_filler: Fill the virtual fields for your Ecto structs and nested structs recursively

See also this GitHub issue that shows that at one point there was a hook, but has been removed:

And also notice that it is a recurring topic with people finding this hook lacking, one example being:

1 Like