CodeSampleX

Sample

ecto 3.14.1: Manage unloaded association state with Ecto.Association.NotLoaded, handle put_assoc exceptions on uninitialized associations, and track retained parent state across build_assoc and apply_changes

Verified sample for hex ecto 3.14.1: Manage unloaded association state with Ecto.Association.NotLoaded, handle put_assoc exceptions on uninitialized…

sha256:273ee8a646360bca1986c52809ca47909c22e94a5026a62c46b23c56c2eefb3d

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
2
Declared environment elixir linux x64 elixir elixir mix

Verification-run environments

Environment Contract Stages Run
elixir 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-17
elixir 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-18

Case

HOW
Goal
Manage unloaded association state with Ecto.Association.NotLoaded, handle put_assoc exceptions on uninitialized associations, and track retained parent state across build_assoc and apply_changes
Packages
Symbols
  • Ecto.Changeset.put_assoc
  • Ecto.Association.NotLoaded
  • Ecto.assoc_loaded?
  • Ecto.build_assoc
  • Ecto.Changeset.apply_changes
Environment
elixir
Created
2026-08-17T04:43:50Z

Contract

  1. Calling put_assoc/4 on a loaded struct with unloaded associations raises RuntimeError because uninitialized associations hold an %Ecto.Association.NotLoaded{} struct rather than nil or [], and Ecto.assoc_loaded?/1 returns false.
  2. Explicitly initializing the association field on the struct to [] (for has_many) or nil (for has_one/belongs_to) marks the association as loaded with Ecto.assoc_loaded?/1 returning true, allowing put_assoc/4 to succeed on loaded structs.
  3. Calling Ecto.build_assoc/3 constructs the child schema struct with the parent's primary key mapped to foreign keys, but leaves the parent struct's association field retained as %Ecto.Association.NotLoaded{}.
  4. Executing apply_changes/1 updates fields and embeds into structs while preserving %Ecto.Association.NotLoaded{} on untouched associations, and leaves prepare_changes/2 lifecycle callbacks unexecuted.
  5. Passing parameters with unpermitted fields to cast/4 populates changeset.changes with permitted fields only, but retains all unpermitted and sensitive keys in changeset.params.

Files

  • NOTES.md
  • csx.json
  • mix.exs
  • mix.lock
  • test/contract.exs
  • test/test_helper.exs

Download the source artifact (tar.gz)

Source

NOTES.md
# Ecto Association Lifecycle and Unloaded Association State

## Search Result
`search_known_solution` returned existing samples for standalone embedded schema validation (`sha256:ec1c423e61b01693526ccce5e694e6c68ed968878f00b8331b3d82c953abea87`), enum type mapping (`sha256:d1e50c1b67c64bb0ab581fa19e909ad51eaa5367d3452a1deaf707f94d0ce9d2`), optimistic locking (`sha256:5d85013b48b55a584df3de5dcf398e0521d62de64604a8a72d8b00bf177082d0`), and parameterized types (`sha256:c069af3c66e9ae5208f2cc544fe78a61db6c37868e4e9a224c66ca6592ead421`). This sample proves the in-memory resource retention and association lifecycle when working with schemas without a database repository: `%Ecto.Association.NotLoaded{}` struct defaults, `put_assoc/4` prerequisites, `build_assoc/3` retention, `apply_changes/1` callback dropping, and raw unpermitted parameter retention in `changeset.params`.

## How the Wrong Version Fails
The wrong expectation fails loudly with a `RuntimeError` (`attempting to cast or change association ... that was not loaded. Please preload your associations before manipulating them through changesets`) when attempting to associate records onto loaded structs, and fails silently in green builds where `prepare_changes/2` callbacks are dropped without execution when applying changes outside of a database repository.
csx.json
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"believed":"A competent developer expects put_assoc/4 to associate child records directly onto any struct or changeset, assuming schema association fields default to empty collections or nil when newly constructed.","caseId":"case:sha256:70ed1aef534530ef457e5097732a1a433fa086068bfddb065a6242329a6b02ae","contract":["Calling put_assoc/4 on a loaded struct with unloaded associations raises RuntimeError because uninitialized associations hold an %Ecto.Association.NotLoaded{} struct rather than nil or [], and Ecto.assoc_loaded?/1 returns false.","Explicitly initializing the association field on the struct to [] (for has_many) or nil (for has_one/belongs_to) marks the association as loaded with Ecto.assoc_loaded?/1 returning true, allowing put_assoc/4 to succeed on loaded structs.","Calling Ecto.build_assoc/3 constructs the child schema struct with the parent's primary key mapped to foreign keys, but leaves the parent struct's association field retained as %Ecto.Association.NotLoaded{}.","Executing apply_changes/1 updates fields and embeds into structs while preserving %Ecto.Association.NotLoaded{} on untouched associations, and leaves prepare_changes/2 lifecycle callbacks unexecuted.","Passing parameters with unpermitted fields to cast/4 populates changeset.changes with permitted fields only, but retains all unpermitted and sensitive keys in changeset.params."],"goal":"Manage unloaded association state with Ecto.Association.NotLoaded, handle put_assoc exceptions on uninitialized associations, and track retained parent state across build_assoc and apply_changes","kind":"HOW","packages":["pkg:hex/ecto@3.14.1"],"schemaVersion":1,"symbols":["Ecto.Changeset.put_assoc","Ecto.Association.NotLoaded","Ecto.assoc_loaded?","Ecto.build_assoc","Ecto.Changeset.apply_changes"]},"contractCommand":["mix","test","--no-deps-check","test/contract.exs"],"environment":{"arch":"x64","ecosystem":"hex","executionContext":"elixir","language":"elixir","os":"linux","packageManager":"mix","runtime":"elixir","schemaVersion":1},"license":"MIT-0","packages":["pkg:hex/ecto@3.14.1"],"schemaVersion":1,"symbols":["Ecto.Changeset.put_assoc","Ecto.Association.NotLoaded","Ecto.assoc_loaded?","Ecto.build_assoc","Ecto.Changeset.apply_changes"],"verifierAdapter":"hex@1"}
mix.exs
defmodule CsxEctoAssocLifecycle.MixProject do
  use Mix.Project

  def project do
    [
      app: :csx_ecto_assoc_lifecycle,
      version: "0.1.0",
      elixir: "~> 1.18",
      deps: deps()
    ]
  end

  def application, do: [extra_applications: []]

  defp deps do
    [{:ecto, "3.14.1"}]
  end
end
mix.lock
%{
  "decimal": {:hex, :decimal, "3.1.1", "430d87b04011ce6cbd4fd205be758311a81f87d552d40904abd00f015935b1d0", [:mix], [], "hexpm", "c5f25f2ced74a0587d03e6023f595db8e924c9d3922c8c8ffd9edfc4498cf1f6"},
  "ecto": {:hex, :ecto, "3.14.1", "7b740d87bdf45996aa0c2c2e081640906f10caa7ce5ba328fd294c7d49d0cc6f", [:mix], [{:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "24b991956796700f467d0a3ef3d303138a3ef9ddddf8b98f43758ee067b20a30"},
  "telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
}
test/contract.exs
ExUnit.start()

defmodule CsxEctoAssocLifecycle.Post do
  use Ecto.Schema
  import Ecto.Changeset

  schema "posts" do
    field :title, :string
    has_many :comments, CsxEctoAssocLifecycle.Comment
    has_one :metadata, CsxEctoAssocLifecycle.PostMetadata
  end

  def changeset(post, params) do
    post
    |> cast(params, [:title])
    |> validate_required([:title])
  end
end

defmodule CsxEctoAssocLifecycle.Comment do
  use Ecto.Schema
  import Ecto.Changeset

  schema "comments" do
    field :body, :string
    belongs_to :post, CsxEctoAssocLifecycle.Post
  end

  def changeset(comment, params) do
    comment
    |> cast(params, [:body])
    |> validate_required([:body])
  end
end

defmodule CsxEctoAssocLifecycle.PostMetadata do
  use Ecto.Schema
  import Ecto.Changeset

  schema "post_metadata" do
    field :view_count, :integer, default: 0
    belongs_to :post, CsxEctoAssocLifecycle.Post
  end

  def changeset(metadata, params) do
    metadata
    |> cast(params, [:view_count])
  end
end

defmodule CsxEctoAssocLifecycle.ContractTest do
  use ExUnit.Case, async: true

  import Ecto.Changeset

  alias CsxEctoAssocLifecycle.Comment
  alias CsxEctoAssocLifecycle.Post
  alias CsxEctoAssocLifecycle.PostMetadata

  test "calling put_assoc/4 on a loaded struct with unloaded associations raises RuntimeError because uninitialized associations hold %Ecto.Association.NotLoaded{} and Ecto.assoc_loaded?/1 returns false" do
    # When a record is loaded (state: :loaded), un-preloaded association fields hold %Ecto.Association.NotLoaded{}
    loaded_post = %Post{id: 1, title: "Elixir Deep Dive"} |> Ecto.put_meta(state: :loaded)

    assert match?(%Ecto.Association.NotLoaded{__field__: :comments, __cardinality__: :many}, loaded_post.comments)
    assert match?(%Ecto.Association.NotLoaded{__field__: :metadata, __cardinality__: :one}, loaded_post.metadata)

    # Ecto.assoc_loaded?/1 returns false for NotLoaded associations
    refute Ecto.assoc_loaded?(loaded_post.comments)
    refute Ecto.assoc_loaded?(loaded_post.metadata)

    # Calling put_assoc/4 on an unloaded association of a loaded record raises RuntimeError
    comment_changeset = Comment.changeset(%Comment{}, %{"body" => "Great read!"})

    assert_raise RuntimeError, ~r/attempting to cast or change association `comments`.*not loaded.*preload/i, fn ->
      loaded_post
      |> change()
      |> put_assoc(:comments, [comment_changeset])
    end

    assert_raise RuntimeError, ~r/attempting to cast or change association `metadata`.*not loaded.*preload/i, fn ->
      loaded_post
      |> change()
      |> put_assoc(:metadata, %PostMetadata{view_count: 10})
    end
  end

  test "explicitly initializing the association field on the struct to [] (for has_many) or nil (for has_one/belongs_to) marks the association as loaded, allowing put_assoc/4 to succeed on loaded structs" do
    # When initialized to [] or nil, Ecto.assoc_loaded?/1 returns true even for loaded structs
    loaded_many_preloaded =
      %Post{id: 1, title: "Elixir Deep Dive", comments: []}
      |> Ecto.put_meta(state: :loaded)

    assert Ecto.assoc_loaded?(loaded_many_preloaded.comments)

    loaded_one_preloaded =
      %Post{id: 1, title: "Elixir Deep Dive", metadata: nil}
      |> Ecto.put_meta(state: :loaded)

    assert Ecto.assoc_loaded?(loaded_one_preloaded.metadata)

    # put_assoc/4 now succeeds on the loaded has_many association
    comment_changeset = Comment.changeset(%Comment{}, %{"body" => "Great read!"})
    changeset_many =
      loaded_many_preloaded
      |> change()
      |> put_assoc(:comments, [comment_changeset])

    assert changeset_many.valid?
    assert [applied_comment_cs] = changeset_many.changes.comments
    assert applied_comment_cs.action == :insert
    assert applied_comment_cs.changes.body == "Great read!"

    # put_assoc/4 succeeds on the loaded has_one association
    meta_changeset = PostMetadata.changeset(%PostMetadata{}, %{"view_count" => 42})
    changeset_one =
      loaded_one_preloaded
      |> change()
      |> put_assoc(:metadata, meta_changeset)

    assert changeset_one.valid?
    assert changeset_one.changes.metadata.action == :insert
    assert changeset_one.changes.metadata.changes.view_count == 42
  end

  test "calling Ecto.build_assoc/3 constructs the child schema struct with parent foreign keys, but leaves parent association field retained as %Ecto.Association.NotLoaded{}" do
    parent = %Post{id: 100, title: "Parent Post"}

    # build_assoc/3 creates a child struct with parent primary key mapped to the foreign key
    built_comment = Ecto.build_assoc(parent, :comments, %{body: "Built comment"})
    assert built_comment.__struct__ == Comment
    assert built_comment.post_id == 100
    assert built_comment.body == "Built comment"

    built_meta = Ecto.build_assoc(parent, :metadata, %{view_count: 5})
    assert built_meta.__struct__ == PostMetadata
    assert built_meta.post_id == 100
    assert built_meta.view_count == 5

    # The parent struct is NOT mutated: its association fields remain %Ecto.Association.NotLoaded{}
    refute Ecto.assoc_loaded?(parent.comments)
    refute Ecto.assoc_loaded?(parent.metadata)
    assert match?(%Ecto.Association.NotLoaded{}, parent.comments)
  end

  test "executing apply_changes/1 updates fields and applied associations into structs while preserving %Ecto.Association.NotLoaded{} on untouched associations, and leaves prepare_changes/2 callbacks unexecuted" do
    post = %Post{id: 1, title: "Initial Title", comments: []}
    comment_cs = Comment.changeset(%Comment{}, %{"body" => "Nested"})

    changeset =
      post
      |> change(%{title: "Updated Title"})
      |> put_assoc(:comments, [comment_cs])
      |> prepare_changes(fn cs ->
        put_change(cs, :title, "From Prepare Callback")
      end)

    # prepare_changes callback is retained in changeset.prepare
    assert length(changeset.prepare) == 1

    # apply_changes/1 applies field changes and nested child structs
    applied = apply_changes(changeset)
    assert applied.title == "Updated Title"
    assert [applied_comment] = applied.comments
    assert applied_comment.__struct__ == Comment
    assert applied_comment.body == "Nested"

    # Untouched association metadata remains %Ecto.Association.NotLoaded{}
    refute Ecto.assoc_loaded?(applied.metadata)
    assert match?(%Ecto.Association.NotLoaded{}, applied.metadata)

    # prepare_changes was NOT executed by apply_changes/1
    refute applied.title == "From Prepare Callback"
  end

  test "passing parameters with unpermitted fields to cast/4 populates changeset.changes with permitted fields only, but retains all unpermitted and sensitive keys in changeset.params" do
    raw_params = %{
      "title" => "Permitted Title",
      "admin_override" => true,
      "secret_token" => "super_secret_value"
    }

    changeset = Post.changeset(%Post{}, raw_params)

    assert changeset.valid?
    # Only permitted fields enter changeset.changes
    assert changeset.changes == %{title: "Permitted Title"}
    refute Map.has_key?(changeset.changes, :admin_override)
    refute Map.has_key?(changeset.changes, :secret_token)

    # But changeset.params retains all raw unpermitted keys
    assert changeset.params["admin_override"] == true
    assert changeset.params["secret_token"] == "super_secret_value"
    assert Map.keys(changeset.params) |> Enum.sort() == ["admin_override", "secret_token", "title"]
  end
end
test/test_helper.exs
ExUnit.start()

Origin Seeder

csx-seed