Linell
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:
- What is the right way to ensure that my
autosum_fieldsmethod runs whenever the opponent is updated? - 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.
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
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
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
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
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
I’ve followed the Phoenix LiveView file upload code here Uploads — Phoenix LiveView v1.0.0-rc.7 and so far everything works just fine wit...
New
Other Trending Topics
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
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
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
Latest Phoenix Threads
Latest on Elixir Forum
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #ai
- #phoenix_html
- #iex
- #elixirconf-us
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming











Showing Posts 1 to 5- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
hauleth
Assuming PostgreSQL as a database.
You have 2 options how to make it “right”:
Both will make your application much clearer and, at least logically, normalise your data.
al2o3cr
If your application doesn’t write directly to the calculated fields, you could do the calculations in the changeset function; use
get_field(changeset, :neutral_losses)and so on and add the resulting values withchange(since they don’t need type-casting).The result is that passing an update to a single field like
%{"away_losses" => 3}gives a changeset that updatesaway_lossesand all the derived values.Linell
I think this is a very cool way to do it and I’m definitely not against the idea, but some of the calculations I want to do in the future are going to be pretty complicated and I feel like I’ll be able to do that better in Elixir than in SQL.
When you say doesn’t write directly to the calculated fields, do you mean that this approach would cause problems with being able to have those values as user input as well? I think I may have used abused the term “calculated field” a bit. I’m looking to be able to fill out a set of data where some fields can fill out others but some of them can be generated based on more basic values, if that helps clarify what I’m thinking.
I like the idea of doing it like this but I’d love a bit more guidance.
How can I get fields for this record that aren’t part of the changeset’s changes? That way I can bail out of the function quickly if the
lossesproperty is already set and I can grab any other values needed for the calculation.shankardevy
get_fieldgets the value from changeset and if the field is not present in changes, then it gets it from the record.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 ignorelosses?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 likewinning_percentage.