Skip to content

Instantly share code, notes, and snippets.

@shankardevy

shankardevy/order.ex Secret

Last active Aug 18, 2017
Embed
What would you like to do?
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
field :comments, :string
field :customer_id, :integer
field :customer_name, :string
field :email, :string
field :residence_area, :string
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
def checkout_changeset(%Order{} = order, attrs) do
changeset(order, attrs)
|> cast(attrs, [:customer_id, :customer_name, :residence_area, :email, :comments])
|> validate_required([:customer_id, :customer_name, :residence_area, :email])
end
end
@thebrianemory

This comment has been minimized.

Copy link

@thebrianemory thebrianemory commented Aug 16, 2017

Hello, there is conflicting information with this gist and what is in the book in Listing 12 and 13 in the Checkout chapter. It is a similar situation for gist https://gist.github.com/shankardevy/9a43b681503fb56effa500e1ed2f9277.

Listing 12
schema "sales_orders" do compared to line 7 above.

Listing 13
|> cast(attrs, [:order_status, :total]) compared to line 23.
|> validate_required([:line_items, :order_status, :total]) compared to line 26 above.

You might already have it fixed in the next revision but just in case. :)

@shankardevy

This comment has been minimized.

Copy link
Owner Author

@shankardevy shankardevy commented Aug 18, 2017

@thebrianemory thanks for the comment. Yes, this has been fixed. Thank you for taking time to inform the error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment