Skip to content

Instantly share code, notes, and snippets.

@zporter
Last active May 17, 2017 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zporter/24dc5d2319dee71db48ba1f4881ba81c to your computer and use it in GitHub Desktop.
Save zporter/24dc5d2319dee71db48ba1f4881ba81c to your computer and use it in GitHub Desktop.
Ecto: Embedded Schemas
use Ecto.Schema
import Ecto.Changeset
@type t :: module
# A required field for all embedded documents
@primary_key {:id, :binary_id, autogenerate: true}
schema "" do
field :street_1, :string
field :street_2, :string
field :city, :string
field :state, :string
field :postal_code, :string
end
@spec changeset(t, %{}) :: Ecto.Changeset.t
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:street_1, :street_2, :city, :state, :postal_code])
|> validate_required([:street_1, :city, :state, :postal_code])
end
schema "orders" do
field :subtotal, :decimal
field :total_tax, :decimal
field :total_shipping, :decimal
field :total_price, :decimal
field :payment_source, :string
field :notes, :string
belongs_to :user, CourseMaster.User
embeds_one :billing_address, CourseMaster.Address, on_replace: :update
embeds_one :shipping_address, CourseMaster.Address, on_replace: :update
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
@spec changeset(t, %{}) :: Ecto.Changeset.t
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:total_price, :total_shipping, :subtotal, :total_tax, :payment_source, :notes])
|> cast_embed(:billing_address, required: true)
|> cast_embed(:shipping_address, required: false)
|> validate_required([:total_price, :subtotal, :payment_source])
end
test "changeset with invalid billing address" do
billing_address_params = %{
street_1: "",
city: "Durham",
state: "NC",
postal_code: "27701"
}
changeset = Order.changeset(
%Order{},
params_for(:order, billing_address: billing_address_params)
)
refute changeset.valid?
assert {:billing_address, {:street_1, ["can't be blank"]}} in errors_on(changeset)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment