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

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
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
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement