overcomeoj

overcomeoj

Get_field returning nil instead of my default

My schema has two numbers, they must add up to 100 on save.

The fields are simple field ... :integer with no defaults, etc.

I have a custom validator, to get the fields and sum them:

  defp validate_sum(changeset) do
    Enum.reduce([:part_a,  :part_b], 0,
      fn key, sum ->
        sum + (get_field(changeset, key, 0)) # drama generator
      end
    )
    |> case do
      100 ->
        changeset
      _ ->
        changeset
        |> add_error(:part_a, "sum of parts must be 100")
        |> add_error(:part_b, "sum of parts must be 100")
    end
  end

My problem is that get_field returns nil, not zero. I think because the key exists, but its value is nil?

I can solve my problem by writing (get_field(changeset, key) || 0), which returns the value if its not nil, or 0.

Is this the correct way of handling this? Is get_field intended to only return it’s “default” value if you try to access a non existent / misnamed field? Why would that be useful?

Marked As Solved

chulkilee

chulkilee

Seems like your analysis is correct.

https://github.com/elixir-ecto/ecto/blob/v3.5.7/lib/ecto/changeset.ex#L1052-L1062

Why would that be useful?

Since ecto can be used for schema-less data - see Schemaless changesets for instance.


Please note that both data and changes fields are “public fields”, so you can just check the field whether you have to run the validation and where to get the value (data vs changes).

Or you can use the value from data as the default value for get_change/3.

Where Next?

Popular in Questions Top

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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
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
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
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
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
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
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement