I do have a problem regarding returning the created id from multi. Here is the sample code:
Ecto.Multi.new
|> Ecto.Multi.insert(:post, %Post{})
|> MyRepo.transaction
But all this does is return changes
. How do I get the created id for it?
I do have a problem regarding returning the created id from multi. Here is the sample code:
Ecto.Multi.new
|> Ecto.Multi.insert(:post, %Post{})
|> MyRepo.transaction
But all this does is return changes
. How do I get the created id for it?
Ecto.Repo.transaction/2 will return an {:ok, changes}
tuple where you can pattern match on the :post change to get the post and pull the id out. This should work:
Ecto.Multi.new
|> Ecto.Multi.insert(:post, %Post{})
|> MyRepo.transaction
|> case do
{:ok, %{post: post} ->
{:ok, post}
{:error, _, reason, _} ->
{:error, reason}
end
As a side note, Ecto.Multis are generally used to make multiple transactions which depend upon each other. If you are only inserting the one post you could use Repo.insert and just pass a changeset or struct.
Oh, right I forgot to pattern match the inside result that’s why I can’t output the post.id
. Thanks @A-Legg