Cast_embed causing error

Hello, I am getting an error from cast_embed, so there is clearly something I don’t understand:

 1) test creates document and renders document when data is valid (Koko.Web.DocumentControllerTest)
     test/koko_web/controllers/document_controller_test.exs:78
     ** (FunctionClauseError) no function clause matching in Ecto.Changeset.cast_embed/3

Here is the relevant code:

schema "documents" do
    field :content, :string
    field :title, :string
    ...
    embeds_many :children, Child
    ...
  end

  def changeset(%Document{} = document, attrs) do
    document
    |> cast(attrs, [:title, :author_id, :content, :rendered_content, :attributes, :tags, :identifier])
    |> cast_embed([:children])
    |> validate_required([:title, :author_id, :content])
  end

The embedded schema is

defmodule Child do
  use Ecto.Schema
  embedded_schema do
    field :level, :integer
    field :title, :string
    field :doc_id, :integer
    field :doc_identifier, :string
  end
end

believe cast_embed expects an atom and not a list https://github.com/elixir-ecto/ecto/blob/master/lib/ecto/changeset.ex#L669

so try:

|> cast_embed(:children)

1 Like

@outlog, Yes, that is definitely the case. Thankyou! I also had to add (per error messages), a changeset to the Child module, like the below. Then everything works.

defmodule Child do
  use Ecto.Schema
  import Ecto.Changeset

  embedded_schema do
    field :level, :integer
    field :title, :string
    field :doc_id, :integer
    field :doc_identifier, :string
  end

  def changeset(%Child{} = child, attrs) do
    child
    |> cast(attrs, [:level, :title, :doc_id, :doc_identifier])
  end

end
1 Like