File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -360,6 +360,16 @@ defmodule PolymorphicEmbed do
360360
361361 to_string ( type_from_parent_field ) != to_string ( type_from_map ) ->
362362 raise "type specified in the parent field \" #{ type_from_parent_field } \" does not match the type in the embedded map \" #{ type_from_map } \" "
363+
364+ true ->
365+ # type_from_parent_field and type_from_map match
366+ module = get_polymorphic_module_for_type ( type_from_parent_field , types_metadata )
367+
368+ if is_nil ( data_for_field ) or data_for_field . __struct__ != module do
369+ { :insert , struct ( module ) }
370+ else
371+ { :update , data_for_field }
372+ end
363373 end
364374 else
365375 case get_polymorphic_module_from_map ( params , type_field_name , types_metadata ) do
Original file line number Diff line number Diff line change @@ -199,6 +199,35 @@ defmodule PolymorphicEmbedTest do
199199 assert { :error , % Ecto.Changeset { } } = insert_result
200200 end
201201
202+ test "infer type from parent field when type in embed map matches parent field type" do
203+ generator = :polymorphic
204+ reminder_module = get_module ( Reminder , generator )
205+
206+ # Both parent field type and embed __type__ are "sms" - they match
207+ sms_reminder_attrs = % {
208+ date: ~U[ 2020-05-28 02:57:19Z] ,
209+ text: "This is an SMS reminder #{ generator } " ,
210+ type: "sms" ,
211+ channel4: % {
212+ __type__: "sms" ,
213+ number: "02/807.05.53" ,
214+ country_code: 1 ,
215+ provider: % {
216+ __type__: "twilio" ,
217+ api_key: "foo"
218+ }
219+ }
220+ }
221+
222+ insert_result =
223+ struct ( reminder_module )
224+ |> reminder_module . changeset ( sms_reminder_attrs )
225+ |> Repo . insert ( )
226+
227+ assert { :ok , % { channel4: % PolymorphicEmbed.Channel.SMS { number: "02/807.05.53" } } } =
228+ insert_result
229+ end
230+
202231 test "validations before casting polymorphic embed still work" do
203232 for generator <- @ generators do
204233 reminder_module = get_module ( Reminder , generator )
You can’t perform that action at this time.
0 commit comments