Ecto validation return nested response with put_assoc

ecto returning nested validation errors

"errors": {
        "registration_number": [
            "can't be blank"
        ],
        "commanall": [
            {
                "email_id": [
                    "can't be blank"
                ],
                "contacts": [
                    {
                        "contact_number": [
                            "can't be blank"
                        ]
                    }
                ]
            }
        ]
    }

but we want response like

"errors": {
        "registration_number": ["can't be blank"],
	"email_id": ["can't be blank"],
       "contact_number": ["can't be blank"]
    }

this is my code

changeset_commanall = Commanall.changeset_company_contact(%Commanall{}, contact_params)
bothinsert = Ecto.Changeset.put_assoc(changeset, :commanall, [changeset_commanall])
Repo.insert(bothinsert)

And where is the response generated? Repo.insert(bothinsert) would return an invalid changeset in case of an error. So you can flatten out the response where you transform the invalid changeset into this json, I assume?.

Have you checked out Ecto.Changeset.traverse_errors? You can just collect all errors as you go and directly convert to the flat map structure you require.

2 Likes