New Ecto "How-To" Guide: Self-referencing many to many

Hi everyone,

Just wanted to say that the new Self-referencing many to many guide is now up on the official Hex docs (at least I just noticed :blush:). If anyone is thinking about (or struggling with) implementing associations that self-reference each other, then I encourage you to check out this guide.

This latest guide is inspired from my own utilization of this association strategy in an upcoming social connection web app built with Elixir and Phoenix — it was forged in fire, so to speak. So, I hope it helps anyone else struggling to implement a similar strategy in their own applications. :heart:

12 Likes

I’m following your guide, which is great - thanks, but am left wondering how you might handle adding multiple records vs a single call to the Relationship changeset.

1 Like

I would use Ecto.Multi, something like:

Ecto.Multi.new()
|> Ecto.Multi.insert(table_name, changeset(struct, attrs))
|> Repo.trasaction()

# So, with the 'relationship' naming:
Ecto.Multi.new()
|> Ecto.Multi.insert(
  :relationships,
  Relationship.changeset(%Relationship{}, attrs)
)
|> Repo.transaction()

If I’m not mistaken, what’s great about it is that you don’t really have to do anything tricky. I haven’t tested this but I think this is a good guide on Ecto.Multi from Elixir School.

** Forgot to include Repo.transaction() :blush:

1 Like