brucepomeroy

brucepomeroy

Sorry I couldn’t come up with a better title for this one!

I’m trying to use an Ecto Changeset to maintain a set of changes provided by a user, eventually, when the user clicks “Save”, the changes will be written to the database but for now I’m trying to use the changes to keep track of all requested changes so I can conditionally show/hide form elements and display validation messages. Each time the user makes a change to a field, I don’t necessarily receive all the params for all the other fields again. So whenever I get a change from the user, I add that change to a changeset that is already tracking all previous changes. I’m getting some unexpected behaviour though. It occurs in the case that the user edits a field of an embedded association, changing it back to its original value.

  defmodule Page do
      use Ecto.Schema
      import Ecto.Changeset


      schema "pages" do
        embeds_one :background, Background, on_replace: :update do
          field :color, :string
         end
         timestamps()
      end

      def background_changeset(schema, params) do
        schema
        |> cast(params, [:color])
      end

      @doc false
      def changeset(schema, attrs) do
        schema
        |> cast(attrs, [])
        |> cast_embed(:background, with: &background_changeset/2)
      end
    end


    test "replacing a change in a changeset" do
      page = %Page{background: %Page.Background{color: "red"}}

      changed_to_blue = Page.changeset(page, %{"background" => %{"color" => "blue"}})
      assert changed_to_blue.changes.background.changes == %{color: "blue"}

      changed_to_green = Page.changeset(changed_to_blue, %{"background" => %{"color" => "green"}})
      assert changed_to_green.changes.background.changes == %{color: "green"}

      changed_back_to_red = Page.changeset(changed_to_green, %{"background" => %{"color" => "red"}})
      assert changed_back_to_red.changes.background.changes == %{color: "red"}

      # Assertion with == failed
      #  code:  assert changed_back_to_red.changes.background.changes == %{color: "red"}
      #  left:  %{color: "green"}
      #  right: %{color: "red"}
    end
  end

As you can see above, we can keep applying new changes to a changeset and they overwrite the previous changes, this is what I want. However, if we try to change the value back to the value contained in the Changeset’s data, the change is ignored.

Does this seem like unexpected behaviour? If so, I can post this as a Github issue for Ecto. Or am I misunderstanding/misusing changesets here?

Thanks!

Showing Posts 1 to 3

LostKobrakai

LostKobrakai

I’m not sure this is fully unexpected behaviour. Generally you want to avoid setting a value as a change if it matches the current value. The difference here is that you already have a change. I’d be curious if the same happens without the embedded schema. If not, then it’s imho a bug because of inconsistency.

For me this kinda strengthens my opinion of changesets being a bad format for accumulating changes in. The other one is the fact that errors are never “revalidated”. I see changesets more as a short lived artefact of changes. You’re using it more like a cache for changes. Imo the cleaner solution would be using e.g. Ecto.Changeset.apply_action to apply changes between each step and use the result for the next changeset as base. Only when it comes to storing the changes fetch from the db again (or store it separately) and create a changeset for the changes between the db stored data and ones you have at runtime.

dimitarvp

dimitarvp

Yep. People trying to use them as long-lived accumulators of changes are in for trouble, as it happened here.

Changesets seem designed for one-off operations.

brucepomeroy

brucepomeroy OP

Thanks for the guidance @LostKobrakai and @dimitarvp. Really appreciate it. Makes a lot of sense. I will try out the suggestion of applying changes each time. Sounds like a good approach!

Incidentally, to answer your question, this only happens when working with nested schemas.

— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
water
I’m aware of 2 such projects, are there others? git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
itzmidinesh
Hi all, I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
leoschweizer
Hi, we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
csmr
Hi all, I’m new here and would like to hear peoples views on my Elixir/Phoenix based game-engine! :smiley: Mutonex gamedesign was finish...
New
Stef-Verniers
Hello I’ve been coding in Elixir for almost two years now because of my current job where we implemented Elixir in our application. But ...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New
kip
In 2021 I started a new library called Tempo with the objective of modelling time as a set of intervals - not as instants. In 2022 I gave...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews