Elixir remove many of many associations

I have two models: user and group. There are many for many connected through the connection table. When I try to delete a user (or group), it causes this error:

** (Ecto.ConstraintError) when trying to delete a model:

* foreign_key: groups_user_id_key

What should I do to remove any parent model?

+4
source share
2 answers

This error will occur in the database, because the link to the user / group that you are trying to delete is stored in the join table. There are several solutions to these problems:

  • You can delete all entries in the connection table before manually deleting the user / group
  • on_delete: :delete_all /
  • ON DELETE CASCADE references(table, on_delete: :delete_all).

Ecto: http://hexdocs.pm/ecto/Ecto.Schema.html#has_many/3 : http://hexdocs.pm/ecto/Ecto.Migration.html#references/2

+9
has_many :groups, MyApp.User, on_delete: :nilify_all

:on_delete

, :

: - ;

: delete_all - ;

: nilify_all - nil ;

: fetch_and_delete - , before_delete after_delete; , has_many/3.

https://hexdocs.pm/ecto/Ecto.Model.Dependent.html

+2

Source: https://habr.com/ru/post/1617616/


All Articles