With these modules:
defmodule Foo do
use Ecto.Schema
import Ecto.Changeset
schema "foo" do
field(:name, :string, null: false)
embeds_many(:bars, __MODULE__.Bar, on_replace: :delete)
end
def changeset(model, params \\ %{}) do
model
|> cast(params, [:name])
|> cast_embed(:bars)
|> validate_required([:name, :bars])
end
end
defmodule Foo.Bar do
use Ecto.Schema
embedded_schema do
field(:bar, :string, null: false)
end
end
I expect the following line to return a “can’t be blank” error for the :bars
field:
%Foo{} |> Foo.changeset(%{name: "foo"})
But instead, I got a valid changeset.
How can I make sure that :bars
is present in the changeset?
I already tried cast_embed(:bars, required: true)
but it doesn’t help.