-
-
Save shankardevy/de6abd4cbc529b310709ca7679c140f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Mango.Sales.Order do | |
use Ecto.Schema | |
import Ecto.Changeset | |
alias Mango.Sales.{Order, LineItem} | |
schema "orders" do | |
embeds_many :line_items, LineItem, on_replace: :delete | |
field :status, :string | |
field :total, :decimal | |
timestamps() | |
end | |
@doc false | |
def changeset(%Order{} = order, attrs) do | |
order | |
|> cast(attrs, [:status, :total]) | |
|> cast_embed(:line_items, required: true, with: &LineItem.changeset/2) | |
|> set_order_total | |
|> validate_required([:status, :total]) | |
end | |
defp set_order_total(changeset) do | |
items = get_field(changeset, :line_items) | |
total = Enum.reduce(items, Decimal.new(0), fn(item, acc) -> | |
Decimal.add(acc, item.total) | |
end) | |
changeset | |
|> put_change(:total, total) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment