首页 > 解决方案 > 如何组合变更集错误?

问题描述

我正在尝试合并变更集错误。

我有一个属于用户模式的机构模式。每个字段都需要一些字段,但错误响应如下所示:

{
    "errors": {
        "user": {
            "password_confirmation": [
                "The password confirmation does not match the password."
            ],
            "password": [
                "This field is required."
            ],
            "name": [
                "This field is required."
            ]
        },
        "institution": {
            "web_address": [
                "is required."
            ]
        },

    }
}

如何将这些错误对象合并为一个?

我的插入看起来像:

 user_changeset =
      User.normal_user_changeset(%User{}, %{
        :email => Map.get(attrs, "email"),
        :password => Map.get(attrs, "password"),
        :password_confirmation => Map.get(attrs, "password_confirmation"),
        :name => Map.get(attrs, "name"),
        :postcode => Map.get(attrs, "postcode"),
        :dob => Map.get(attrs, "dob")
      })

    institution =
      %Institution{}
      |> Institution.changeset(%{
        :web_address => Map.get(attrs, "web_address"),
        :person_responsible => Map.get(attrs, "person_responsible"),
        :annual_turnover => Map.get(attrs, "annual_turnover")
      })
      |> Ecto.Changeset.put_assoc(:user, user_changeset)
      |> Repo.insert()

我希望错误响应是:

 {
        "errors": {
                "password_confirmation": [
                    "The password confirmation does not match the password."
                ],
                "password": [
                    "This field is required."
                ],
                "name": [
                    "This field is required."
                ]
                "web_address": [
                    "is required."
                ]
        }
    }

我的后备控制器中有这个功能(默认情况下):

  def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
    conn
    |> put_status(:unprocessable_entity)
    |> render(SfiWeb.ChangesetView, "error.json", changeset: changeset)
  end

标签: elixirphoenix-framework

解决方案


您可以errors使用以下方法获取字段的值并将它们全部合并Enum.reduce/3

map = Jason.decode! """
{
    "errors": {
        "user": {
            "password_confirmation": [
                "The password confirmation does not match the password."
            ],
            "password": [
                "This field is required."
            ],
            "name": [
                "This field is required."
            ]
        },
        "institution": {
            "web_address": [
                "is required."
            ]
        }
    }
}
"""

Map.update!(map, "errors", fn errors ->
  errors |> Map.values() |> Enum.reduce(%{}, &Map.merge/2)
end)
|> IO.inspect

输出:

%{
  "errors" => %{
    "name" => ["This field is required."],
    "password" => ["This field is required."],
    "password_confirmation" => ["The password confirmation does not match the password."],
    "web_address" => ["is required."]
  }
}

推荐阅读