Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elixir delete many to many association

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?

like image 548
user3546621 Avatar asked Nov 26 '15 12:11

user3546621


2 Answers

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:

  • You can delete all the join table entries before deleting user/group by hand
  • You can set the on_delete: :delete_all option for the join model association in your group/user schema
  • You can set the ON 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

like image 125
michalmuskala Avatar answered Nov 15 '22 21:11

michalmuskala


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

like image 2
Alex Troush Avatar answered Nov 15 '22 19:11

Alex Troush