How to control flow with `with-do` statement

Hi everyone.

I am new to start programming with Elixir and Phoenix. I have a problem with with-do statements when control my actions flow.
Like this

with {:ok, %Product{} = product} <- Sales.create_product(attrs),
        {:ok, %ProductVariation{} = product_variation} <- Sales.create_first_product_variation(product),
        {:ok, _} <- Sales.create_link_between_product_and_category(product, category_id) do
    conn
    |> put_status(:created)
    |> json(%{success: true, product: product})
end

What should I do if the second or the third pattern is not matched? The product have an unique field then user can not recreate it with the same info. Should I delete the product when creating product variation is failed? or there is a better way to implement it? Can I init a bunch of data for user with with-do statement? Eg create account -> create subscription -> create inventory …etc…

Sorry for many questions :frowning:

Thank you.

1 Like

I have found this article. This is exactly what i looking for. Sorry for create topic without searching. :frowning:
https://hackernoon.com/using-ecto-multi-for-complex-database-transactions-70aac419e81c

2 Likes

Yup! Ecto.Multi is the way to go to solve that problem.

You may also want to have a look at this project I saw recently: Sage

Ecto.Multi in combination with Sage seems like it could be quite useful in many situations like this.

1 Like

This looks like a good one as well.

Claudio is a smart fellow who’s been doing this a while.

2 Likes