Linell

Linell

Creating Autosumming Fields

I’ve created an Opponent model that has several fields associated with it, each of which represents an actual or computed value. You can check out the whole file as it exists right now here, but the schema itself looks like this:

  schema "opponents" do
    field :name,                :string
    field :external_id,         :string
    field :away_losses,         :float
    field :away_wins,           :float
    field :home_losses,         :float
    field :home_wins,           :float
    field :losses,              :float
    field :neutral_losses,      :float
    field :neutral_wins,        :float
    field :opp_opp_winning_pct, :float
    field :opp_winning_pct,     :float
    field :winning_percentage,  :float
    field :wins,                :float

    belongs_to :dataset, Scorcerer.Datasets.Dataset

    timestamps()
  end

Some of the fields are dependent on each other - for example for there to be a winning_percentage there have to be wins and losses. Others can bet set or not and it doesn’t really matter that much - we can compute wins from home_wins and away_wins even if neutral_wins is nil. Right now I’ve got it setup to handle all of that via functions like this:

  def autosum_fields(opponent) do
    if opponent.wins == nil do
      set_wins(opponent)
    end

    if opponent.losses == nil do
      set_losses(opponent)
    end

    if opponent.winning_percentage == nil do
      set_winning_percentage(opponent)
    end
  end

  defp set_winning_percentage(opp) do
    if (opp.wins != nil && opp.losses != nil) do
      Scorcerer.Opponents.update_opponent(opp, %{ winning_percentage: opp.wins / opp.losses })
    end
  end

  defp set_wins(opp) do
    wins = Enum.reduce([:home_wins, :away_wins, :neutral_wins], 0, fn key, acc ->
      key_value = Map.get opp, key
      acc + (key_value || 1)
    end)

    Scorcerer.Opponents.update_opponent(opp, %{ wins: wins })
  end

  defp set_losses(opp) do
    losses = Enum.reduce([:home_losses, :away_losses, :neutral_losses], 0, fn key, acc ->
      key_value = Map.get opp, key
      acc + (key_value || 1)
    end)

    Scorcerer.Opponents.update_opponent(opp, %{ losses: losses })
  end

I’ve actually got two questions here:

  1. What is the right way to ensure that my autosum_fields method runs whenever the opponent is updated?
  2. Is there a better way to handle the actual updates? I know I’m doing more updates than is required right now because it’s happening on a per-field basis.

Most Liked

shankardevy

shankardevy

get_field gets the value from changeset and if the field is not present in changes, then it gets it from the record.

hauleth

hauleth

Assuming PostgreSQL as a database.

You have 2 options how to make it “right”:

  • Views in the DB (potentially materialised)
  • If you are on Postgres 12+ then you can use generated fields

Both will make your application much clearer and, at least logically, normalise your data.

Last Post!

al2o3cr

al2o3cr

Yes - if the fields are writable directly, you’ll need to decide what happens when incompatible parameters are assigned; for instance, %{home_losses: 10, away_losses: 5, losses: 3}. Should that ignore losses?

Also consider if directly writing to the fields (even ones like home_losses) is the best approach; if data arrives incrementally (one result at a time) you might instead want operations like “record this game was a win at home” that manipulate multiple fields and recalculate things like winning_percentage.

Where Next?

Popular in Questions Top

vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
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
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
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
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
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

Other popular topics Top

jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 44608 311
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
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
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

We're in Beta

About us Mission Statement