How do you create associations using a through table IF the required info exists?

Let’s say you have Movie and Category tables. A Movie can have many categories and a Category can have many movies.

When I create a new Movie I have params coming in like this

%{title: "Movie title", categories: [%{id: 1}] }

I have a uniqueness constraint in the movies_categories table to prevent duplicates being created on [:movie_id, :category_id]

I was wondering how do you all like to create associations when there’s a join table and a uniqueness constraint on it?

I was hoping to use a Ecto.Multi but if I try to create a MovieCategory where one already exists or if my params come in with:

%{title: "Movie title", categories: [] } # no category

Then I’m not sure how to prevent the transaction from being rolled back. A goal I would like is to have the transaction of update/create of a movie not be rolled back if the category is already associated or if there is no category in the params.

Just looking for the idiomatic elixir/ecto way of handling this. I can certainly do this with multiple transactions but… would like one transaction if possible.

Thank you

1 Like