Ecto Changesets — put, cast, embeds and assocs. Remember the difference once and for all!

defmodule DinnerGuest do
use Ecto.Schema
schema "dinner_guests" do
field(:name, :string)
end
end
defmodule DinnerGuest do
use Ecto.Schema
embedded_schema do
field(:name, :string)
end
end
defmodule DinnerGuest do
use Ecto.Schema
schema "dinner_guests" do
field(:name, :string)
has_one(:aurora_borealis, AuroraBorealis)
has_many(:steamed_hams, SteamedHam)
end
end
defmodule DinnerGuest do
use Ecto.Schema
embedded_schema do
field(:name, :string)
embeds_many(:steamed_hams, SteamedHam)
embeds_one(:aurora_borealis, AuroraBorealis)
end
end
data = %{
dinner_date: "2018-01-01",
name: "Super Nintendo Chalmers",
other: "Random data",
}
defmodule DinnerGuest do
defstruct [:name, :dinner_date]
def new(data) do
struct(DinnerGuest, data)
end
end
%DinnerGuest{
name: "Super Nintendo Chalmers",
dinner_date: "2018-01-01"
}
defmodule DinnerGuest do
use Ecto.Schema

embedded_schema do
field(:name, :string)
field(:dinner_date, :date)
end
def new(data) do
struct(DinnerGuest, data)
end
end
Ecto.Changeset.cast(%DinnerGuest{}, data, [:name, :dinner_date])
|> Ecto.Changeset.apply_changes
%DinnerGuest{
name: "Super Nintendo Chalmers",
dinner_date: ~D[2018-01-01]
}
Ecto.Changeset.change(%DinneGuest{})
|> Ecto.Changeset.cast_assoc([%{"meat_type" => "medium rare"}])
existing_relations = [%{id: 1, meat_type: "rare"}]Ecto.Changeset.change(%DinneGuest{})
|> Ecto.Changeset.cast_assoc(
existing_relations ++ [%{"meat_type" => "medium rare"}]
)
%SteamedHam{}
|> Ecto.Changeset.cast(data, [:meat_type])
|> Ecto.Changeset.put_assoc(:dinner_guest, dinner_guest)
|> Repo.insert!()

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store