View Source Goal.Changeset (goal v0.1.1)

Goal.Changeset contains an adapted version of Ecto.Changeset.traverse_errors/2.

You can use traverse_errors/2 to build all errors into a series of nested maps.

Link to this section Summary

Functions

Traverses changeset errors and applies the given function to error messages.

Link to this section Types

@type action() :: nil | :insert | :update | :delete | :replace | :ignore | atom()
@type constraint() :: %{
  type: :check | :exclusion | :foreign_key | :unique,
  constraint: String.t(),
  match: :exact | :suffix | :prefix,
  field: atom(),
  error_message: String.t(),
  error_type: atom()
}
@type data() :: map()
@type error() :: {String.t(), Keyword.t()}
@type t() :: t(Ecto.Schema.t() | map() | nil)
@type t(data_type) :: %Ecto.Changeset{
  action: action(),
  changes: %{optional(atom()) => term()},
  constraints: [constraint()],
  data: data_type,
  empty_values: term(),
  errors: [{atom(), error()}],
  filters: %{optional(atom()) => term()},
  params: %{optional(String.t()) => term()} | nil,
  prepare: [(t() -> t())],
  repo: atom() | nil,
  repo_opts: Keyword.t(),
  required: [atom()],
  types:
    nil
    | %{required(atom()) => Ecto.Type.t() | {:assoc, term()} | {:embed, term()}},
  valid?: boolean(),
  validations: [{atom(), term()}]
}
@type types() :: map()

Link to this section Functions

Link to this function

traverse_errors(changeset, msg_func)

View Source
@spec traverse_errors(
  t(),
  (error() -> String.t()) | (Ecto.Changeset.t(), atom(), error() -> String.t())
) :: %{required(atom()) => [term()]}

Traverses changeset errors and applies the given function to error messages.

This function is particularly useful when associations, embeds, maps and nested maps are cast in the changeset as it will traverse all associations, embeds, maps and nested maps and place all errors in a series of nested maps.

A changeset is supplied along with a function to apply to each error message as the changeset is traversed. The error message function receives an error tuple {msg, opts}, for example:

{"should be at least %{count} characters", [count: 3, validation: :length, min: 3]}

examples

Examples

iex> traverse_errors(changeset, fn {msg, opts} ->
...>   Regex.replace(~r"%{(\w+)}", msg, fn _, key ->
...>     opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
...>   end)
...> end)
%{title: ["should be at least 3 characters"]}

Optionally function can accept three arguments: changeset, field and error tuple {msg, opts}. It is useful whenever you want to extract validations rules from changeset.validations to build detailed error description.

This function and documentation is gratefully copied and adapted from Ecto.Changeset.traverse_errors/2 🙇