Creating Autosumming Fields

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.

  def set_losses(changeset) do
    # TODO: bail out if losses is already set
    autosum_fields = MapSet.new([:home_losses, :away_losses, :neutral_losses])
    changed_fields = changeset.changes |> Map.keys |> MapSet.new

    fields_that_matter = MapSet.intersection(m1, m2) |> Enum.count

    if fields_that_matter > 0 do
      # TODO: grab other fields from the database related to this record and
      # do calculations

      losses = do_calculations
      changeset = change(changeset, losses: losses) # is this correct?
    end
  end

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 losses property is already set and I can grab any other values needed for the calculation.