acke

acke

Hi, I’m working through the PragProg “Programming Elixir LiveView” book and encountered a strange bug when implementing a changeset. The changeset is as follows:

 def lower_price_changeset(product, new_price) do
    old_price = product.unit_price
    product
    |> change(unit_price: new_price)
    |> validate_number(:unit_price, less_than: old_price)
  end

When I run the function using a product struct with the same unit price as new price, a valid schema where no changes are made is generated (see below). If I run the function using a new_price which is greater than product.unit_price, an invalid schema is generated so I assume that my logic is solid.

iex(52)> p
%Pento.Catalog.Product{
  __meta__: #Ecto.Schema.Metadata<:built, "products">,
  id: nil,
  description: nil,
  name: nil,
  sku: nil,
  unit_price: 9.0,
  inserted_at: nil,
  updated_at: nil
}
iex(53)> Pento.Catalog.Product.lower_price_changeset(p, 9.0) 
#Ecto.Changeset<action: nil, changes: %{}, errors: [],
 data: #Pento.Catalog.Product<>, valid?: true>

Am I missing something obvious or is this a bug? In that case, is there a workaround? I know that float comparison isn’t straightforward so perhaps this causes the issue?

Showing Posts 1 to 10

03juan

03juan

In the docs for change it says Changed attributes will only be added if the change does not have the same value as the field in the data.

So in this case I don’t think the validation is run because the unit price hasn’t changed.

jerdew

jerdew

I don’t often use change/2 so I went to the docs and noticed this:

Changed attributes will only be added if the change does not have the same value as the field in the data

9.0 == 9.0 so there is no change. maybe try:

product
|> change() # make a changeset
|> put_change(:unit_price, new_price)
03juan

03juan

Actually put_change also says If the change has the same value as in the changeset data, it is not added to the list of changes.

I’ve checked the source for validate_number and it uses validate_change internally, which also states

It invokes the validator function to perform the validation only if a change for the given field exists and the change value is not nil .

03juan

03juan

The best bet would probably be writing your own validator that adds a changeset error if the values match, or then invokes the validate_number(... less_than: old_priced)

acke

acke OP

Thanks for the answers, good to know that this is the intended functionality at least. Do you think it’d be the “correct” solution to implement my own validator or to simply return an empty changeset? I feel that the code would become worse if I were to implement an essentially identical version of a library function but on the other hand it is inefficient to keep the execution going knowing that no changes will be made. I’m not entirely sure how Ecto translates this to the database level but I can imagine that it is handled in an efficient manner and that the performance penalty is not that big.

dimitarvp

dimitarvp

I am not sure what else should Ecto be doing, can you specify your expected behavior?

But if you really really want to flag a field as changed there’s always Ecto.Changeset.force_change.

acke

acke OP

I expected an invalid changeset yo be generated, as it does when I give set the new_price parameter to a number which is greater than old_price. Intuitively it doesn’t make sense to me why the cases new_price > old_price and new_price = old_price would yield different given the validate_number call in my original post.

dimitarvp

dimitarvp

Ah yes, I thought there was also an equal sign there. Did you try with force_change and see if the validator gets tripped then?

03juan

03juan

I really depends on your use case. What I’m assuming is you want the changeset to throw an error when new >= old.

It will throw an error when new > old because change(unit_price: new_price) marks unit_price as changed and therefore validate_number(:unit_price, less_than: old_price) runs against the changed value.

But change won’t mark the attribute as changed if new = old and therefore it won’t ever run validate_number.

This is probably your best bet

because ecto not seeing the change is a feature to prevent unnecessary db writes when the value wouldn’t change, but you can still force it with force_change.

Otherwise you could add a custom error when the prices are equal and let the normal validation take care of the less_than case. (this is what I actually meant by custom validation, sorry for the confusion)

def lower_price_changeset(product, new_price) do
  old_price = product.unit_price
  product
  |> change(unit_price: new_price)
  |> error_on_equal_or_less_than(old_price, new_price)
end

defp error_on_equal_or_less_than(changeset, old_price, old_price) do
  add_error(changeset, :unit_price, "is equal to old price", old_price: old_price)
end

defp error_on_equal_or_less_than(changeset, old_price, _) do
  validate_number(changeset, :unit_price, less_than: old_price)
end

The changeset won’t show the price changed in the changes: key, but it will have it in the error and the changeset won’t be valid, so you can adapt your business and application logic to match on it.

#Ecto.Changeset<action: nil,
 changes: %{},
 errors: [unit_price: {"is equal to old price", [old_price: 9.0]}],
 data: #Pento.Catalog.Product<>,
 valid?: false>
dimitarvp

dimitarvp

Oh right, maybe it would have helped if I paid a little more attention. You are 100% correct.

I’d also advise for a custom validator function in this case. It’s no big deal and I don’t know why people are so averse to it; it’s just a pipe of functions as all others in Elixir. But I do get it, some get cold feet because previous frameworks gave them PTSD. Can relate!

Though in this case I’d make a custom validator that replaces Ecto’s validate_number + less_than in one fell swoop, i.e. makes the check and either adds an error or just returns the original changeset.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
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
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews