Ecto validation failing even when change is present

I’m trying to persist a record created with this changeset:

 def changeset(record_or_changeset, params) do
    record_or_changeset
    |> cast(params, ~w[customer_id price]a)
    |> validate_required(~w[customer_id price]a)
  end

I run this changeset whenever the user updates the form and then again when they hit save. However, Repo.insert/1 is returning this error:

{:error,
 #Ecto.Changeset<
   action: :insert,
   changes: %{
     customer_id: "81a25893-2da0-4754-9032-de1e32b06078",
     price: #Decimal<25>
   },
   errors: [price: {"can't be blank", [validation: :required]}],
   data: #MyApp.Price<>,
   valid?: false
 >}

I don’t understand why I’m getting this particular error when price is specifically included in the changes?

Hey @travisf can you show how your changeset function is being called? Are you perhaps reusing a changeset already had errors on it?

Ah @benwilson512 that was it! I thought that passing a %Changeset{} into the changeset/2 function it would update/remove any existing errors but I guess that wouldn’t be a very immutable pattern.

1 Like

Ahhh yeah the design of changesets is such that if you want to “try again” you make a new one with whatever new parameters you’ve got. Glad I could get you unstuck!

1 Like