Embedded Schema: Is parent schema valid?

Hi everyone,

I have an embedded_schema, which again uses embed_one. I don’t want to save the child, when a certain key name isn’t set. I have the following code, which works great, with one exception:

When the parent changeset is invalid, the nil value will break the auto-generated forms, inputs_for won’t show the fields anymore. So I only want to perform this action when I know that the parents are valid and the update to the database will happen.

Is there a way to do this?

embedded_schema do
  embeds_one :element_a, Element, on_replace: :delete
  embeds_one :element_b, Element, on_replace: :delete
end

def changeset(%__MODULE__{} = thing, params) do
  thing
  |> cast(params, [])
  |> cast_embed(:element_a)
  |> cast_embed(:element_b)
  |> remove_if_empty(:element_a)
  |> remove_if_empty(:element_b)
end

defp remove_if_empty(changeset, field) do
  case get_field(changeset, field) do
    %{name: nil} ->
      put_embed(changeset, field, nil) # Check if parents are valid?
    _ ->
      changeset
  end
end
1 Like