Preload associations in embeds?

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 from Foo 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

You cannot have associations in embeds, as this is not something databases support.

@LostKobrakai what about this? https://github.com/elixir-ecto/ecto/pull/3368

That’s interesting. The fact still stands though in that it’s not a foreign key association, which is what one usually understands here.

However given this now exists. Are you on ecto 3.5?

Yes Ecto 3.5. Maybe I did something obviously wrong, Ecto is quite complex. But now I’m really stuck with these errors.

Great news! Associations work inside of embeds. You have a small typo.

:country should be :countries. :slight_smile:

I compiled it and it ran fine.