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?