我从数据库返回了不同的结构,我想用所有自定义值(例如Ecto.Assoication.Notloaded
)替换值not loaded
。
这是一条记录
unit = %{
__meta__: #Ecto.Schema.Metadata<:loaded, "units">,
cdc_location_class_id: nil,
description: "",
facility: #Ecto.Association.NotLoaded<association :facility is not loaded>,
facility_id: 2215,
id: 719,
is_active: true,
name: "Unit",
rooms: #Ecto.Association.NotLoaded<association :rooms is not loaded>
}
这是我想要的地图
unit = %{
__meta__: #Ecto.Schema.Metadata<:loaded, "units">,
cdc_location_class_id: nil,
description: "",
facility: "not loaded">,
facility_id: 2215,
id: 719,
is_active: true,
name: "Unit",
rooms: "not loaded"
}
有什么建议吗?
谢谢
答案 0 :(得分:1)
我将使用:maps.map/2
,在value参数上进行模式匹配,并在必要时将其替换:
new_unit =
:maps.map(fn
_, %Ecto.Association.NotLoaded{} -> "not loaded"
_, value -> value
end, unit)
如果您需要在地图列表上运行此代码,只需将以上内容放入函数中并使用Enum.map/2
。
答案 1 :(得分:0)
由于结构只是地图,因此它们可与Map模块中的功能一起使用
因此,您可以使用Map.put替换该值。这是示例:
defmodule Test do
defmodule User do
defstruct name: "John", age: 27
end
def test() do
a = %User{}
IO.inspect a
a = Map.put(a, :name, "change")
IO.inspect a
end
end
Test.test()
答案 2 :(得分:0)
您可以尝试以下操作:
unit = %{
__meta__: #Ecto.Schema.Metadata<:loaded, "units">,
cdc_location_class_id: nil,
description: "",
facility: #Ecto.Association.NotLoaded<association :facility is not loaded>,
facility_id: 2215,
id: 719,
is_active: true,
name: "Unit",
rooms: #Ecto.Association.NotLoaded<association :rooms is not loaded>
}
unit = case Ecto.assoc_loaded?(unit.facility) do
false -> Map.put(unit, :facility, "not loaded")
_ -> unit
end