Data/changes in Changeset

This is a two part question. To preface; I have a form that handles creating and updating information. When a user updates information, the information is loaded as a struct into a changeset, at which point the information is kept in changeset.data. But once the form processes the information somehow, the information is moved over to changeset.changes (because the information is now given as parameters, not a struct).

So my first question is: is there a way to trick changeset to view the initial struct as changed information, so that it ends up changeset.changes?

Second question: I wrote a workaround in the code, which I feel is ugly. Can someone tell me if there is a better way of writing something like this?

updated_links =
      socket.assigns.changeset.changes
      |> Map.has_key?(:links)
      |> case do
        true ->
          socket.assigns.changeset.changes.links
          |> Enum.concat([new_link])
        false ->
          socket.assigns.changeset.data.links
          |> Enum.concat([new_link])
      end

Checking if the key exists and then branching from that feels very imperative.

You almost never want to reach inside a Changeset struct (apart from things like matching on valid?) - prefer functions like Changeset.get_field/3 that handle the details.

2 Likes