An equivalent to Rails' after_save in Phoenix

I have an order model and line_items model. I want simply to calculate line_items prices (for associated order) and save the sum value to total field in order. How to do that? What is the equivalent to Rails after_save callback (I want to calculate the sum of line_item’s prices after saving the order)?

Callbacks where removed from ecto long ago. Explicitly call a function to do the calculation, possibly harnessing Ecto.Multi.

2 Likes

I have read about Ecto but cannot understand how to use it when creating or updating records. If anyone has some sample code, please share it here, I will highly appreciate that. Thank you :slight_smile:

I guess this example illustrates the usage:

user_changeset = User.changeset(%User{}, user_params)multi =
  Multi.new
  |> Multi.insert(:user, user_changeset)
  |> Multi.run(:address, fn %{user: user} ->
    address_changeset = 
      %Address{user_id: user.id}
      |> Address.changeset(address_params)
    Repo.insert(address_changeset)
  end)case Repo.transaction(multi) do
  {:ok, result} ->
    {:ok, jwt, _full_claims} = 
      Guardian.encode_and_sign(result.user, :token)    conn
    |> put_status(:created)
    |> render(MyApp.SessionView, "create.json", jwt: jwt, user: result.user)  {:error, :user, changeset, %{}} ->
    conn
    |> put_status(:unprocessable_entity)
    |> render(MyApp.RegView, "error.json", changeset: changeset)  {:error, :address, changeset, %{}} ->
    conn
    |> put_status(:unprocessable_entity)
    |> render(MyApp.RegView, "error.json", changeset: changeset)
end

1 Like