[Solved] Nilify many-to-many relationships on update

Hello,
I feel I’m missing something here. I’m working on a quite large database (200 tables) with lots of relationships between models. All the forms get the whole model with all its relations loaded and sends back the whole model with its relations updated.
I’m using helpers to fetch or create associated models before calling put_assoc.
I’d like to fluidify a bit the process of manually deleting entries before calling put_assoc on many-to-many relationships.

For example, an Event has many Images but the Images can be shared with other models.
To update an Event, I manually delete entries in the events_images table with the relevant event id.
I do this (and am gonna have to do this) for every relation that is updatable via a form submission.

My question is : is there an obvious alternative that I’m missing ? The docs don’t seem to suggest that there would be.

I already have an helper App.Repo.nilify_many(table, primary_key, id) to make this process less manual, but I’d hope for an Ecto native solution.

Have a nice day.

You might want to take a look at has_many …, through:

1 Like

Whoops, thank you.
I don’t know why this didn’t occur, I’m already manually specifying join tables everywhere like this :

 many_to_many :images, App.Contents.Image,
      join_through: "events_images",
      join_keys: [event_id: :id, image_id: :id]

    many_to_many :workers, App.General.Entity,
      join_through: "events_workers",
      join_keys: [event_id: :id, entity_id: :id]

    many_to_many :partners, App.General.Entity,
      join_through: "events_partners",
      join_keys: [event_id: :id, entity_id: :id]

So it seems this wouldn’t be a large change.

Edit: it seems this paragraph I missed contains the answer to my original question : https://hexdocs.pm/ecto/Ecto.Schema.html#many_to_many/3-removing-data . I must have misread it, because it’s quite explicit on the subject. This was a case of “writing the problem to others solves it”.
Have a nice day !

1 Like