Nested Embedded Schema Changeset

Hi all, I have a nested embedded schema like this

embedded_schema do

embeds_many :chart, Chart do
  field(:vendor, :string)
  field(:type, :string)
  field(:background_color, :string)
  field(:border_color, :string)
  field(:plot_background_color, :string)
  field(:height, :string)
  field(:width, :string)      


I don’t know how to make the changeset for this.Please help.

You need to create the Chart module, which will contain… embedded_schema and changeset. Create the changeset as You would for any schema.

And in the master schema, use embeds_many, then use put_change on the master changeset

Ecto.Changeset.put_change(changeset, :charts, charts)
1 Like

Inline embeds and their changesets are explained here:


This might help you get your head around it.

In short the answer is you create them similar to how you would a usual assoc. In ecto there are associations (think has_one, has_many) and there are embeds (think embeds_one, embeds_many). Each of those has their own function for creating a changeset; cast_assoc and cast_embed. In your case you probably want a cast_embed

1 Like

Just to post the example from the documentation so that it’s immediately clear how to do this (I still had to spend some time finding the answer even after reading through this thread):

def changeset(schema, params) do
  |> cast(params, [:name])
  |> cast_embed(:child, with: &child_changeset/2)

defp child_changeset(schema, params) do
  |> cast(params, [:name, :age])

In short, you’ll need to call the cast_embed function and provide the changeset function defined for the embedded schema under the with: key.

1 Like