代码之家  ›  专栏  ›  技术社区  ›  script

用自定义值替换结构中的特定值

  •  0
  • script  · 技术社区  · 6 年前

    我从数据库返回了不同的结构,我想替换这个值 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"
    }
    

    谢谢

    3 回复  |  直到 6 年前
        1
  •  1
  •   Dogbert    6 年前

    我会用 :maps.map/2 ,模式匹配值参数,并根据需要替换它:

    new_unit =
      :maps.map(fn
        _, %Ecto.Association.NotLoaded{} -> "not loaded"
        _, value -> value
      end, unit)
    

    Enum.map/2

        2
  •  0
  •   chris    6 年前

    因为结构只是映射,所以它们使用来自映射模块的函数

    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()
    
        3
  •  0
  •   Lucas Franco    6 年前

    您可以尝试以下方法:

    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