It is possible to make an insert and build associations of this insert in the same transaction?

I’m starting with associations and transactions in Phoenix, it is possible to make an insert and put associations (for this insert) in the same transaction ? or I need to make the insert before and get the id of this insert ?

Yes, possible. Within the transaction you can get the id of the insert.

1 Like

If you use Phoenix, then probably you use Ecto as well. If not, you should, Ecto is amazing.
Check Ecto Multi.

2 Likes

cast_assoc and put_assoc also insert the data inside the same transaction

2 Likes

Thank you How ?

Yes I use Ecto Multi :wink:

OK thank you :slight_smile:

So, this code would be correct ?

build_assoc belongs to Ecto or Ecto.Changeset ?

Multi.new()
|> Multi.insert(:insert, %Post{})
|> build_assoc(:comments)
|> build_assoc(:pictures)
|> Repo.transaction

Hi @sabo66 please do not make 4 individual posts to reply, just make one post and quote people you want to reply to inside.

I think you’re overthinking this.

  1. If you use the assoc helpers a regular Repo.insert(post) call will open a transaction and insert any children in the changeset in the same transaction, so that’ll just work
  2. If you want to do this manually I would consider first trying to do so without any transaction, then figure out how to do it inside a transaction.
3 Likes

Ok !

Ok thank you, I understand better now @benwilson512 :slight_smile: