tozz

tozz

I’m pretty sure I’m in XY-Problem land right now, but here goes (I have shortened the code as much as possible to keep it focused).

I have a Ecto schema (SubMetric), with a simple
has_many :values, SubMetricValues, on_replace: :delete

I also have a list that is dynamic in nature, let’s say it contains ["a", "b", "c"] called configured_ranges below.

Now I want to make sure that when creating a new SubMetric, or editing one the values are in sync based on the list. In my SubMetric changeset I to the usual casting etc and then I have a function specifically for this case (I figured keeping this in the schema is the best place to avoid code duplication or forgetting to trigger the sync behavior).

def changeset(sub_metric, attrs \\ %{}) do
    sub_metric
    |> cast(attrs, [:metric_id, :name, :identifier, :static])
    |> validate_required([:metric_id, :name, :identifier, :static])
    |> cast_assoc(:values)
    |> synchronize_ranges()
  end

  defp synchronize_ranges(changeset) do
    current_values = get_field(changeset, :values, [])
    configured_ranges = ["a", "b", "c"]
    # The "range" key is one of the values from the configured_ranges
    current_ranges = Enum.map(current_values, & &1.range)

    updated_values =
      current_values
      |> Enum.filter(&(&1.range in configured_ranges))
      |> then(fn existing_values ->
        new_ranges = configured_ranges -- current_ranges
        new_values = Enum.map(new_ranges, &%{range: &1, value: 0})
        existing_values ++ new_values
      end)

    put_assoc(changeset, :values, updated_values)
    # Here the changeset is empty when editing, no changes are registered, which means the form later in the interface gets reset to the values it had when created.
  end

Any ideas? It’s a bit of a strange case I guess, adding dynamic fields from scratch using sort params etc are simple, but here I need the database to contain a specific set of values based on external sources.

Showing Posts 1 to 3

dimitarvp

dimitarvp

Try not using cast_assoc at all? You’re overriding it immediately anyway by using put_assoc right after.

tozz

tozz OP

That won’t work, I need it for validation and making the proper changesets from the values. And it’s not necessarily so that any changes have been done on the values.

I actually managed to make it work by changing the synchronize_ranges function into

defp synchronize_age_ranges(changeset) do
    current_values = get_field(changeset, :values, [])
    configured_ranges = dynamic_list_of_ranges()
    current_ranges = Enum.map(current_values, & &1.range)

    if current_ranges -- configured_ranges != [] || configured_ranges -- current_ranges != [] do
      updated_values =
        current_values
        |> Enum.filter(&(&1.range in configured_ranges))
        |> then(fn existing_values ->
          new_ranges = configured_ranges -- current_ranges
          new_values = Enum.map(new_ranges, &%{range: &1, value: 0})
          existing_values ++ new_values
        end)

      put_assoc(changeset, :values, updated_values)
    else
      changeset
    end
  end

Still feels a bit cumbersome, but this covers new entries, existing ones without modification of the ranges and when removing/adding a range and editing it (or not).

The easier way would probably to be use a Multi, I don’t find this code very readable. But still curious as if to there’s better ways, can’t be that rare that you want to populate rows based on something from “outside” the context of the database.

tozz

tozz OP

Here’s an English example, to avoid looking at my crazy code :smiley:

You have a Game
Each Game have Participants
Participants can join and leave games, when they leave their score is removed and when they join it’s set to zero.
The Partipants are supplied to the Game from an external resource.

— 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
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
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
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
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
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
aseigo
ICal is a library for interacting with iCalendar data. It parses iCalendars into typed Elixir structs via ICal.from_ics, and can prepare ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews