fireproofsocks

fireproofsocks

Adding calculated field on save

I’m working on a table to store shipping addresses. I would like to add a fingerprint of each address so that I can more easily tell whether or not a given address has already been added. For simplicity, let’s assume that I’ve worked out a nice fingerprinting algorithm to normalize my addresses and identify them via a single string… let’s say this function is named simply fingerprint(address).

My question is about Ecto and changesets: how and where can I add this field to the database record when I save it? I’m unclear on how the cast and other functions are working inside the changeset function.

If I try to save a new address and its fingerprint matches an existing address, the save operation should fail.
If I try to edit an existing address and change it so it matches an existing address, the update operation should fail.

Any help on this would be appreciated… I’m having a hard time wrapping my head around where to add this and how to think about it in an idiomatic way. Thanks!

Most Liked

kokolegorille

kokolegorille

Probably something like this…

  @doc false
  def changeset(whatever, attrs) do
    whatever
    |> changeset(attrs)
    |> cast(attrs, @fields)
    |> validate ...
    |> fingerprint()
    |> unique_constraint(:fingerprint, message: "Fingerprint already in use")
  end

  defp fingerprint(changeset) do
    case changeset do
      %Ecto.Changeset{valid?: true, changes: %{address: address}} ->
        put_change(changeset, :fingerprint, create_fingerprint(address))
      _ ->
        changeset
    end
  end

  defp create_fingerprint(address) do
    # Implement your fingerprint here
  end

It is not tested, and fields might not correspond to your structure, but You can get the idea… the 2 last lines from changeset are important.

kokolegorille

kokolegorille

This should not work… as it should be a field

You should use

%Ecto.Changeset{valid?: true, changes: %{street1: street1, street2: street2...}}

# or

%Ecto.Changeset{valid?: true, changes: address}

In the example I gave, whatever is the shemas, and address is just a field of %Whatever{}

You might find ecto changeset structure here. From docs…

changes - The changes from parameters that were approved in casting

kokolegorille

kokolegorille

You might show your schema, and migration file. Be sure :fingerprint field exists, as string…

You might also insert some IO.inspect in your pipeline to show the changeset, like so

  def changeset(whatever, attrs) do
    whatever
    |> changeset(attrs)
    |> cast(attrs, @fields)
    |> validate ...
    |> IO.inspect()
    |> fingerprint()
    |> IO.inspect()
    |> unique_constraint(:fingerprint, message: "Fingerprint already in use")
  end

The function fingerprint take a changeset, and if it is valid, it should persists the change.

If it is clearer, You could have used pattern matching, like so.

defp fingerprint(%Ecto.Changeset{valid?: true, changes: %{address: address}} = changeset) do
  put_change(changeset, :fingerprint, create_fingerprint(address))
end
defp fingerprint(changeset), do: changeset

BTW Try to change the name of the function to generate_fingerprint(), just to be sure it does not conflict with the field name.

Last Post!

fireproofsocks

fireproofsocks

Thank you all! I got it working and I learned a lot in the process – inspecting the changeset with IO.inspect() was helpful because I could see the diffs and where fields were being included in or omitted from the changeset. I ran into a bit of trouble because I had set a default value for country, so that would cause that key to be missing from the changeset. Similarly, with the optional “street2” value, if it was sent with a blank value or omitted entirely, the changeset would end up without that field.

Where Next?

Popular in Questions Top

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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
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
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
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
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

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
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
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

We're in Beta

About us Mission Statement