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

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
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
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews