CheersThankYou

CheersThankYou

Ecto Embedded Schema always register change with changeset

I have an embedded schema, and I noticed that it was always writing to the DB, even when it wasn’t updated from its default value [].

Checking with changeset, it appears to always register it as a change. Where am I going wrong with this?

You can test this in debug using the example:

defmodule Order do
  use Ecto.Schema

  schema "orders" do
    embeds_many :items, Item
  end
end

defmodule Item do
  use Ecto.Schema

  embedded_schema do
    field :title
  end
end
# create a blank changeset
order = %Order{}
orderChange = Ecto.Changeset.change(order)

orderChange |> Ecto.Changeset.put_change(:items, [])

I’ve tried this with a regular blank map, but it only appears to be occurring with an embedded_schema. I feel like I’m missing something obvious here.

First Post! Switch mode

dimitarvp

dimitarvp

If you change this:

embeds_many :items, Item

to this:

embeds_many :items, Item, default: []

…is the problem still there?

Most Liked

CheersThankYou

CheersThankYou

You can replicate the code in my original example in an IEX interactive shell.

I’ve done some more playing about with it in iex and here is the process I took:

defmodule Order do
  use Ecto.Schema

  schema "orders" do
    embeds_many :items, Item, on_replace: :delete #added on_replace to allow manipulation
  end
end

defmodule Item do
  use Ecto.Schema

  embedded_schema do
    field :title
  end
end

With zero items attached to the order:

order = %Order{}
changesetWithNoItems = Ecto.Changeset.change(order)

changesetWithNoItems.data
%Order{__meta__: #Ecto.Schema.Metadata<:built, "orders">, id: nil, items: []}

# this doesn't make sens
changesetWithNoItems |> Ecto.Changeset.put_change(:items, [])
#Ecto.Changeset<
  action: nil,
  changes: %{items: []},
  errors: [],
  data: #Order<>,
  valid?: true
>

# Makes sense
changesetWithNoItems |> Ecto.Changeset.put_change(:items, nil)
#Ecto.Changeset<
  action: nil,
  changes: %{},
  errors: [items: {"is invalid", [type: {:array, :map}]}],
  data: #Order<>,
  valid?: false
>

# Makes sense 
changesetWithNoItems |> Ecto.Changeset.put_change(:items, [%Item{id: 1, title: "test"}])
#Ecto.Changeset<
  action: nil,
  changes: %{
    items: [
      #Ecto.Changeset<action: :insert, changes: %{}, errors: [], data: #Item<>,
       valid?: true>
    ]
  },
  errors: [],
  data: #Order<>,
  valid?: true
>

Then with an order that has a single item attached:


order = %Order{items: [%Item{id: 1, title: "what"}]}
changesetWithItem = Ecto.Changeset.change(order)

changesetWithItem.data 
%Order{
  __meta__: #Ecto.Schema.Metadata<:built, "orders">,
  id: nil,
  items: [%Item{id: 1, title: "what"}]
}

# Makes sense
changesetWithItem |> Ecto.Changeset.put_change(:items, [%Item{id: 1, title: "what"}])
#Ecto.Changeset<action: nil, changes: %{}, errors: [], data: #Order<>,
 valid?: true>

# Doesn't make sense
 changesetWithItem |> Ecto.Changeset.put_change(:items, [%Item{id: 1, title: "huh"}]) 
#Ecto.Changeset<action: nil, changes: %{}, errors: [], data: #Order<>,
 valid?: true>

# confirming
 (changesetWithItem |> Ecto.Changeset.put_change(:items, [%Item{id: 1, title: "huh"}])).data
%Order{
  __meta__: #Ecto.Schema.Metadata<:built, "orders">,
  id: nil,
  items: [%Item{id: 1, title: "what"}]
}

# Doesn't make sense
changesetWithItem |> Ecto.Changeset.put_change(:items, [%Item{id: 2, title: "huh"}])
#Ecto.Changeset<
  action: nil,
  changes: %{
    items: [
      #Ecto.Changeset<action: :replace, changes: %{}, errors: [], data: #Item<>,
       valid?: true>,
      #Ecto.Changeset<action: :insert, changes: %{}, errors: [], data: #Item<>,
       valid?: true>
    ]
  },
  errors: [],
  data: #Order<>,
  valid?: true
>

# Confirming
((changesetWithItem |> Ecto.Changeset.put_change(:items, [%Item{id: 1, title: "huh"}, %Item{id: 2, title: "something new"}])).changes.items |> hd).data
%Item{id: 1, title: "huh"}

Last Post!

Adzz

Adzz

I think this bit:

# this doesn't make sens
changesetWithNoItems |> Ecto.Changeset.put_change(:items, [])
#Ecto.Changeset<
  action: nil,
  changes: %{items: []},
  errors: [],
  data: #Order<>,
  valid?: true
>

Makes sense because you are effectively telling Ecto to delete all the relations (or embeds in this case). Meaning it is always a change I think.

I also think you shouldn’t use put_change but should use cast_embed or put_embed for embeds, that may be the source of the confusion.

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement