diff --git a/lib/ash/type/union.ex b/lib/ash/type/union.ex index 5098eb99f..9ca0969d1 100644 --- a/lib/ash/type/union.ex +++ b/lib/ash/type/union.ex @@ -665,6 +665,7 @@ defmodule Ash.Type.Union do end) do old_values_by_type = old_values + |> List.wrap() |> Stream.with_index() |> Stream.map(fn {item, index} -> Map.put(item, :__index__, index) @@ -803,6 +804,7 @@ defmodule Ash.Type.Union do end) do old_values_by_type = old_values + |> List.wrap() |> Stream.with_index() |> Stream.map(fn {item, index} -> Map.put(item, :__index__, index) diff --git a/test/type/union_test.exs b/test/type/union_test.exs index 31b56d64f..49c3f9d90 100644 --- a/test/type/union_test.exs +++ b/test/type/union_test.exs @@ -62,7 +62,7 @@ defmodule Ash.Test.Type.UnionTest do change fn changeset, _ -> new_thing = Ash.Changeset.get_argument(changeset, :new_thing) - things = Ash.Changeset.get_attribute(changeset, :things) + things = Ash.Changeset.get_attribute(changeset, :things) || [] Ash.Changeset.change_attribute( changeset, @@ -71,6 +71,10 @@ defmodule Ash.Test.Type.UnionTest do ) end end + + update :add_things do + accept [:things] + end end attributes do @@ -361,4 +365,57 @@ defmodule Ash.Test.Type.UnionTest do |> Ash.Changeset.for_update(:add_thing, %{new_thing: %{type: :foo, foo: "foo"}}) |> Ash.Test.AnyApi.update() end + + test "it should handle union arguments appropriately" do + assert {:ok, _} = + Example + |> Ash.Changeset.for_create(:create, %{things: []}) + |> Ash.Test.AnyApi.create!() + |> Ash.Changeset.for_update(:add_thing, %{ + new_thing: %Ash.Union{type: :foo, value: %{type: :foo, foo: "foo"}} + }) + |> Ash.Test.AnyApi.update() + end + + test "it should cast union arguments appropriately when the array is nil" do + assert {:ok, _} = + Example + |> Ash.Changeset.for_create(:create, %{}) + |> Ash.Test.AnyApi.create!() + |> Ash.Changeset.for_update(:add_thing, %{new_thing: %{type: :foo, foo: "foo"}}) + |> Ash.Test.AnyApi.update() + end + + test "it should handle union arguments appropriately when the array is nil" do + assert {:ok, _} = + Example + |> Ash.Changeset.for_create(:create, %{}) + |> Ash.Test.AnyApi.create!() + |> Ash.Changeset.for_update(:add_thing, %{ + new_thing: %Ash.Union{type: :foo, value: %{type: :foo, foo: "foo"}} + }) + |> Ash.Test.AnyApi.update() + end + + test "it should handle union attribute" do + assert {:ok, _} = + Example + |> Ash.Changeset.for_create(:create, %{}) + |> Ash.Test.AnyApi.create!() + |> Ash.Changeset.for_update(:add_things, %{ + things: [%Ash.Union{type: :foo, value: %{type: :foo, foo: "foo"}}] + }) + |> Ash.Test.AnyApi.update() + end + + test "it should handle union attribute appropriately when the array is nil" do + assert {:ok, _} = + Example + |> Ash.Changeset.for_create(:create, %{}) + |> Ash.Test.AnyApi.create!() + |> Ash.Changeset.for_update(:add_things, %{ + things: [%Ash.Union{type: :foo, value: %{type: :foo, foo: "foo"}}] + }) + |> Ash.Test.AnyApi.update() + end end