I can get my example to work if I pass in the Tag structs, but that requires a database call to get them. I feel like it should be possible to pass in the ID’s as that’s all that’s being added to the underlying join table…?
If the comment is already persisted to the database, then put_assoc/4 only takes care of guaranteeing that the comments and the parent data are associated. This extremely useful when associating existing data, as we will see in the “Example: Adding tags to a post” section.
When only passing the ID it would try to insert a new record into the associating table (Tags in this case), but I only want to associate to existing Tag records.
My apologies, I didn’t think my answer through as you specifically didn’t want to make another DB call if you already know the tag ids.
In that case, once you create your comments and have their ids, you can Repo.insert_all/3 directly into the many-to-many table.
It expects a schema module (MyApp.User) or a source (“users”) or both ({“users”, MyApp.User}) as the first argument. The second argument is a list of entries to be inserted, either as keyword lists or as maps.