How to access the Changset Error Value?

How to access the Changset Error that I will receive. Following is the changeset I received

#Ecto.Changeset<
  action: :insert,
  changes: %{
    company_admin_id: 1,
    employment_type: "Part Time",
    maxsalary: #Decimal<123>,
    minsalary: #Decimal<-1>,
    name: "asfsdf",
    workspace_id: 1
  },
  errors: [
    minsalary: {"Min. Salary should be greater than 0",
     [validation: :number, kind: :greater_than, number: 0]}
  ],
  data: #Apollo.JobOpening.Schema.JobOpening<>,
  valid?: false
>

Sometime, Minsalary is Maxsalary, then the error value(like here- Min. Salary should be greater than 0) is different. I want to access the error value, how can I do that? Your response will be highly appreciable.

This way, I guess:

changeset = User.changeset(%User{}, %{age: 0, email: "mary@example.com"})
{:error, changeset} = Repo.insert(changeset)
changeset.errors #=> [age: {"is invalid", []}, name: {"can't be blank", []}]

https://hexdocs.pm/ecto/Ecto.Changeset.html

And then

{message, _value} = changeset.errors[:minsalary]
IO.inspect(message)
2 Likes

Changeset.traverse_errors might be another option as well.

5 Likes