0

I have different structs returned from database and i want to replace the value Ecto.Assoication.Notloaded with some custom value like not loaded in all of them.

This is one record

 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>
}

This is the map I want

 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"
}

Any suggestions?

Thanks

1
  • 1
    "Don't do it" would be my suggestion :) If you need to do it, you are probably doing something wrong. Commented Sep 4, 2018 at 10:20

3 Answers 3

1

I'd use :maps.map/2, pattern match on the value argument, and replace it as necessary:

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

If you need to run this on a list of maps, just put the above in a function and use Enum.map/2.

Sign up to request clarification or add additional context in comments.

1 Comment

You also could use the standard Enum.map function instead of :maps.map, couldn't you? But I guess you would have to add another Enum.into
0

since structs are just maps, they work with the functions from the Map module

So you can use Map.put to replace the value. Here is the example:

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()

Comments

0

You can try something like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.