I have two models: User and Group. They are many to many associated through a join table. When I try to delete a user ( or a group), it raises this error:
** (Ecto.ConstraintError) constraint error when attempting to delete model:
* foreign_key: groups_user_id_key
What should I do to delete any of the parent model?
The database will raise such an error, because the join table still holds a reference to the user/group you're trying to delete. There are multiple solutions to that issues:
on_delete: :delete_all
option for the join model association in your group/user schemaON DELETE CASCADE
option in the database via migrations in the definition for the foreign key constraint with references(table, on_delete: :delete_all)
.You can find out more about this in the Ecto documentation here: http://hexdocs.pm/ecto/Ecto.Schema.html#has_many/3 and here: http://hexdocs.pm/ecto/Ecto.Migration.html#references/2
has_many :groups, MyApp.User, on_delete: :nilify_all
:on_delete
options
There are four different behaviors you can set for your associations when the parent is deleted:
:nothing - Does nothing to the association;
:delete_all - Deletes all associations without triggering lifecycle callbacks;
:nilify_all - Sets model reference to nil for each association without triggering any lifecycle callback;
:fetch_and_delete - Explicitly fetch all associations and delete them one by one, triggering any before_delete and after_delete callbacks; Keep in mind these options are only available for has_many/3 macros.
https://hexdocs.pm/ecto/Ecto.Model.Dependent.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With