Junaid Farooq
Junaid Farooq

Reputation: 2608

extracting strings after traversing errors in Ecto Elixir

As in Ecto, we have changeset and in the case of invalid changeset, we can traverse errors according to Traverse error. But this gave us a very complicated JSON such as

  {
    "to_date": [
      "can't be blank"
    ],
    "title": [
      "can't be blank"
    ],
    "requested_by": [
      "can't be blank"
    ],
    "from_date": [
      "can't be blank"
    ],
    "exid": [
      "can't be blank"
    ]
  }

can't we do something wth that in Elixir so we can get the straight strings such as "Exid can't be blank" or such as an object

{
  to_date: "to_date can't be bank"
}

Update: This is the result after traversing errors

%{exid: ["can't be blank"], from_date: ["can't be blank"],
  requested_by: ["can't be blank"], title: ["can't be blank"],
  to_date: ["can't be blank"]}

is there any way to get "exid cant be blank" by using Enum?

Upvotes: 2

Views: 409

Answers (1)

Dogbert
Dogbert

Reputation: 222398

If you want to convert it to a list of strigs, you can do something like:

for {key, values} <- errors, value <- values, do: "#{key} #{value}"

Demo:

iex(1)> errors = %{exid: ["can't be blank", "can't be something else"], from_date: ["can't be blank"],
...(1)>   requested_by: ["can't be blank"], title: ["can't be blank"],
...(1)>   to_date: ["can't be blank"]}
%{exid: ["can't be blank", "can't be something else"],
  from_date: ["can't be blank"], requested_by: ["can't be blank"],
  title: ["can't be blank"], to_date: ["can't be blank"]}
iex(2)> for {key, values} <- errors, value <- values, do: "#{key} #{value}"
["exid can't be blank", "exid can't be something else",
 "from_date can't be blank", "requested_by can't be blank",
 "title can't be blank", "to_date can't be blank"]

Upvotes: 2

Related Questions