How to return the updated collection after an Ecto insert?


I’m learning Ecto but I’m struggling to find an example that matches my use case. I have a schema called “Flow” a flow can have many “Routes”. I’d like to add a route to the flow then return the new, updated flow including the new route record.

I can add a new route to the flow like so:

    |> Ecto.build_assoc(:routes)
    |> Ecto.Changeset.change(from_id: from_page_id, to_id: to_page_id)
    |> Repo.insert!()

Now I’d like to return the updated flow object. Should I call the DB again?

Repo.get_by(Flow, id: flow_id)

Or, manually add the returned route to the collection with update_in?

Both feel wrong. Ideally, Ecto would return the flow, including the new route.

Thanks for any help.

You probably need to set the read_after_writes to true for the schema’s fields You want to reload…

How does read_after_writes behave in the following case?
As I understand in this example you’d add it to the flow field, and it would load in the field in the result of the insert.
How about if flow has some other relation that you’d like to be loaded in as well, is that possible?