mathieuprog / polymorphic_embed

Polymorphic embeds in Ecto
Apache License 2.0
341 stars 63 forks source link

traverse_errors/2 doesn't seem to work when run on a top-level schema which has_many children schemas that have polymorphic embeds #72

Closed x-ji closed 6 months ago

x-ji commented 2 years ago

An example:

defmodule A.Parent do
  # ...
  schema "parents" do
    has_many(:children, A.Child)
  end

  def changeset(%__MODULE__{} = struct, attrs) do
    struct
    |> cast_assoc(:children)
  end
end

defmodule A.Child do
  schema "children" do
    # ...

    polymorphic_embeds_one(:something, )
  end
end

params = %{
  # ...
  children: [
    %{
      something: ... # Here contains an error
    },
    %{
      something: ...
    }
  ]
}

When a changeset is inserted directly at the Parent level, but contains errors in the polymorphic embed of something at the Child level, PolymorphicEmbed.traverse_errors/2 when run on the resulting changeset still returns an empty map.

Not sure if Ecto.Changeset.traverse_errors/2 has the same behavior. At least the documentation of the Ecto function says

Traverses changeset errors and applies the given function to error messages.

This function is particularly useful when associations and embeds are cast in the changeset as it will traverse all associations and embeds and place all errors in a series of nested maps.

mathieuprog commented 2 years ago

Can you test if the behavior is different? Replace the polymorphic embed by embeds_one and look for differences?

mathieuprog commented 6 months ago

Fixed traverse_errors.