How to create and insert a Many to Many association

how to create associations using between two tables that have _many_to_many_ related using the ecto new many_to_many ?

I have one to many relationships from organization to user:

 organization = Organization.shortcode_changeset(%Organization{}, org_field) organization = organization |> Repo.insert! organization |> build_assoc(:users) 

which gives

 %User{__meta__: #ecto.Schema.Metadata<:built, "users">,......} user = Repo.preload(user, [:organization, :usergroup]) 

How can I do this with many_to_many between users and groups?

+5
source share
2 answers

Here is how I did it:

 user = user |> Repo.preload(:groups) %Group{} |> Group.changeset(@group_field) |> Repo.insert! |> Repo.preload(:users) |> change |> put_assoc(:users, [user]) |> Repo.update 

I could only do this after I found this article that allowed me to continue: http://blog.roundingpegs.com/an-example-of-many-to-many-associations-in-ecto-and-phoenix/

+2
source

Assuming you have an org organization name and a user with the username you want to create a relationship between you, you will take the following steps to get the association created in the change set

 changeset = Repo.preload(org, :users) # load the :users for the org |> Organization.changeset(%{}) # somehow generate a changeset with no changes |> Ecto.Changeset.put_assoc(:users, [user]) # creates the association 

Then all you have to do is apply the set of changes as usual. those.

 Repo.update(changeset) 
+1
source

All Articles