elixir - 如何组合变更集错误?
问题描述
我正在尝试合并变更集错误。
我有一个属于用户模式的机构模式。每个字段都需要一些字段,但错误响应如下所示:
{
"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
解决方案
您可以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."]
}
}
推荐阅读
- sql - 如果外键是另一个表的主键,为什么它可以为空?
- visual-c++ - 出现错误 LNK2019:使用 MSVC 在 Windows 中编译 SDL2 代码时出现无法解析的外部符号
- c - Why `pow(sum,1/2)` is not giving me the same result as `sqrt(sum))`?
- firebase - Flutter/Firebase 实时数据库:如何使用 equalsTo?
- listview - TListView 项目详细字体到等宽字体
- selenium - Chrome Webdriver 出现奇怪错误 | 硒
- sql-server - SQL Group By 分区 By
- reactjs - React Native localhost 另一个调试器已经连接
- c# - 如何将文本框中的文本写入 Visual Basic 中位于 c:\words.txt 上的现有 .txt 中的新行
- javascript - Konva.js 图像出现在桌面但不是移动设备