Deleting nested embeds_many entries

I have a schema with embeds_one field that has few embeds_many sub-entities and am trying to get CRUD working on one of them. So far so good for all but delete, I tried to do this like that (thread):

a safer solution, which is actually recommended and documented by Ecto, is to use a virtual delete field on embedded schema’s changeset function.

so I add a virtual delete field to the embedded schema as well as a maybe_mark_for_deletion function like in the documentation. Now after I submit the form with a delete field checked I get this error:

cannot delete related %Some.Schema.Deeply.Nested.Embed{...} because 
it already exists and it is not currently associated with the given struct. 
Ecto forbids casting existing records through the association field for security reasons. 
Instead, set the foreign key value accordingly

This is a long message, I read it few times but can’t figure out what it means in my case - it’s an embed and not an association, it has no foreign key, it’s one of existing embeds_many that I want to remove.

What am I doing wrong here?

Currently I solved it by filtering out the deleted entries on update action which works fine and is not terrible but doesn’t feel completely clean - I’d prefer to do everything in changesets unless there is no easy fix.

1 Like

ok, let’s put it this way: can anyone explain what the below error message normally means? Is it about attempting to delete technically unrelated data?

Answering my own question: it happens when the changes are passed incorrectly - some of the ids are missing and the changeset detects wrong action (e.g. insert instead of update). With correct changeset data the trick works fine with nested embeds.

1 Like