Ecto build_assoc with multiple models at once

253 Views Asked by At

In Ecto.build_assoc/3, is it possible to pass a list of models as the 3rd argument? Assuming I have a product model which has a many_to_many relationship with a categories model, and 3 existing categories that I would like to associate with this product, is it possible to do something like this:

product = Repo.get!(Product, 1)
#assume the below function exists and returns a list of categories
categories = Category.get_children(:fashion)

#here, the docs say the third parameter can be a map/keyword list of attributes, but thats ok if you are associating a single model. In my case, I have many so am trying to pass a list of maps(structs for that matter)
assocs = Ecto.build_assoc(product, :categories, categories)

Can the above code work?

0

There are 0 best solutions below