tozz

tozz

Populating Ecto has_many based on "external" data and then keeping the two in sync

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.

Most Liked

tozz

tozz

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.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New

Other popular topics Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement