diff --git a/lib/polymorphic_embed.ex b/lib/polymorphic_embed.ex index f1744d1..438d634 100644 --- a/lib/polymorphic_embed.ex +++ b/lib/polymorphic_embed.ex @@ -372,7 +372,7 @@ defmodule PolymorphicEmbed do type_field_name: type_field_name } = field_opts - list_data_for_field = Map.fetch!(changeset.data, field) + list_data_for_field = Map.fetch!(changeset.data, field) || [] embeds = Enum.map(list_params, fn params -> diff --git a/test/polymorphic_embed_test.exs b/test/polymorphic_embed_test.exs index 811d94c..171048b 100644 --- a/test/polymorphic_embed_test.exs +++ b/test/polymorphic_embed_test.exs @@ -1669,6 +1669,7 @@ defmodule PolymorphicEmbedTest do address: "address" } ], + contexts2: nil, contexts3: [ %{ __type__: "device", @@ -1784,6 +1785,27 @@ defmodule PolymorphicEmbedTest do ] } + assert {:ok, _} = + reminder + |> reminder_module.changeset(attrs) + |> Repo.update() + + # Make sure it works for embeds with nil entries + attrs = %{ + contexts2: [ + %{ + __type__: "device", + ref: "12345", + type: "cellphone" + }, + %{ + __type__: "device", + ref: "56789", + type: "laptop" + } + ] + } + assert {:ok, _} = reminder |> reminder_module.changeset(attrs)