user2290820
user2290820

Reputation: 2759

How to build and insert a Many to Many association

how to ​build associations​ using between two tables that have a ​_many_to_many_​ relationship using ecto's new many_to_many feature?

I have one to many relationship 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 a many_to_many between users and groups ?

Upvotes: 7

Views: 4845

Answers (2)

Sam Mercier
Sam Mercier

Reputation: 193

Assuming you have some organization name org and a user named user that you want to build an association between you will take the following steps to get create the association in the changeset

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 left to do is apply the changeset like you normally would. i.e.

Repo.update(changeset)

Upvotes: 1

user2290820
user2290820

Reputation: 2759

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 was able to do this only after I found this article which enabled me to proceed: http://blog.roundingpegs.com/an-example-of-many-to-many-associations-in-ecto-and-phoenix/

Upvotes: 4

Related Questions