The Group has an assosiation with Student, many_to_many
So, when I want to remove the association between two existing structures, I do this:
# student_id is the struct that I want to remove from the association with group.
new_students = Enum.filter(group.students, fn student -> student.id !== student_id end)
group
|> Ecto.Changeset.change()
|> Ecto.Changeset.put_assoc(:students, new_students)
|> Repo.update!()
This is the best practise ? because I feel unconfortable looping over all the associations.
Why would he violate a foreign key constraint? OP has a junction table, let’s say “groups_students”, and removing an association of “groups” and “students” is as simple as deleting a record in the junction table.
P.S. Set to nilify if you don’t care about data integrity.