Ecto: Inserting associated rows transactionally

Ecto is able of inserting entire association graphs (since 2.0, since 1.0 except belongs_to associations) in the correct order inside a transaction, filling foreign keys where necessary. So the simplest solution to your question is:

user = Repo.insert!(%User{authentications: [%Authentication{provider: "facebook"}]})
```

When using changesets, you'll find functions like `put_assoc` (used when programatically manipulating associations), and `cast_assoc` (used when you want to handle associations coming in external params) handy.

When you need more control, either explicit "by-hand" transaction with `Repo.transaction/2` or `Ecto.Multi` is the way to go.
2 Likes