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 ?
When you need to establish a many-to-many relationship between two or more tables, the simplest way is to use a Junction Table. A Junction table in a database, also referred to as a Bridge table or Associative Table, bridges the tables together by referencing the primary keys of each data table.
Many-to-many (M:M) A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa. To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.
If that sounds abstract, let's look at a specific example: Suppose you have a list of students and a list of classes. There's a many-to-many relationship between the students and their classes, since each student can take multiple classes, and each class can have multiple students enrolled.
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/
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With