Say I have the following schemas:
defmodule Articles do
schema "articles" do
field(:name, :string)
embeds_one(:foo, Foo)
end
def changeset(struct, attrs) do
struct
|> cast(attrs, [:name])
|> cast_embed(:foo)
end
end
defmodule Foo do
@primary_key false
embedded_schema do
field(:name, :string)
belongs_to(:country, Country)
end
def changeset(struct, attrs) do
struct
|> cast(attrs, [:name])
|> cast_assoc(:country)
end
end
defmodule Country do
schema "countries" do
field :name, :string
end
end
If I try to run the code below, I’ll have the error:
** (RuntimeError) attempting to cast or change association
country
fromFoo
that was not loaded. Please preload your associations before manipulating them thr
ough changesets
attrs = %{
name: "An article",
foo: %{
country: %{name: "Fiji"}
}
}
%Article{}
|> Article.changeset(attrs)
|> Repo.insert!()
If I try to preload:
%Article{}
|> Repo.preload([foo: :country])
I’ll have the error:
** (ArgumentError) schema Article does not have association :foo