How to understand the position of the element with error when we use cast_assoc

Hello everyone

I have an order and order_items

I create an order through the order changeset itself,

Inside the order changeset I have a cast_assoc to create order_items

Let’s say I create an order that contains 5 order_items

How do I know which order_item the error occurred in?

As I understand it, you can insert order_items through ecto_multi, that is, inserting each order_item is a separate operation with its own name, for example order_item_1, order_item_2, order_item_3 …

But maybe there are other ways without ecto_multi?

When using cast_assoc and there are errors in any of them there will be a list of nested changesets in parent_changeset.changes.assoc_name. You can look at those to figure out which one was the problem. Ecto.Changeset.traverse_errors will also retain that nesting.

1 Like