marick

marick

Many-to-many associations in phoenix and ecto

I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a novice, I probably got some things wrong. Please correct me.

http://blog.roundingpegs.com/an-example-of-many-to-many-associations-in-ecto-and-phoenix/

Most Liked

marick

marick

I think I’ve figured it out.

# Create the user. Note that the (empty) `organizations` field has to be preloaded.
user_map = %{display_name: "User 1", login_name: "1@y.com", password: "password"}
changeset = User.password_setting_changeset(%User{}, user_map)
user = Repo.insert!(changeset) |> Repo.preload(:organizations)

# Do the same for the organization:
org = %Eecrit.Organization{short_name: "org1", full_name: "Organization 1"}
org = Repo.insert!(org) |> Repo.preload(:users)

# Update one of the two of them:
changeset = Ecto.Changeset.change(user) |> Ecto.Changeset.put_assoc(:organizations, [org])

# When you save this change to the user, the join table will have its foreign keys populated in both directions.
Repo.update!(changeset)

Pretty slick.

windholtz

windholtz

Thats a good start at documenting the many_to_many macro.
If anyone can point the way, I’m looking for some description of how to use many_to_many in CRUD operations with change_sets.

The example you give is the way I am using many_to_many also. But if we need to manage the join table manually like that, I’m not seeing how this is any different that defining has_many on both sides.

Is there a developers guide somewhere that shows usage for the many_to_many macro?

from: Ecto.Schema — Ecto v3.14.0
It gives examples on how to get data back out.

# Get all comments for a given post
post = Repo.get(Post, 42)
tags = Repo.all assoc(post, :tags)

# The comments can come preloaded on the post struct
[post] = Repo.all(from(p in Post, where: p.id == 42, preload: :tags)) 
post.tags #=> [%Tag{...}, ...]

But what I’m completely stumped about is how to add, update, and delete data from a many_to_many.

josevalim

josevalim

Creator of Elixir

Hi everyone, sorry for being late to the discussion. If the documentation is incomplete, pull requests are always welcome! I have already improved those examples in the docs though. :slight_smile:

I have also removed the restriction that associated entries need to be changesets. We will now convert them implicitly.

Where Next?

Popular in Questions Top

beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
yawaramin
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function: -dialyzer...
New

Other popular topics Top

Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement