hariharasudhan94
How to get struct from map - elixir?
Lets say i have map like this fetching from my database
%{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => "XXXX@gmail.com", "name" => "Hariharasudhan", "password_hash" => "XXXX", "phone" => "XXXX"}
and i have struct like follow
> @primary_key{:id, :binary_id, autogenerate: true}
schema “users” do
field :name, :string
field :email, :string
field :phone, :string
field :password_hash, :string
end’
what is best way to convert Map to User Struct,
note:
i need to do this convertion on each request after authentication , so i need effective way to achieve this?
Marked As Solved
hubertlepicki
I use this code.
with original version coming from:
https://groups.google.com/forum/#!msg/elixir-lang-talk/6geXOLUeIpI/L9einu4EEAAJ
Also Liked
manukall
That’s what https://hexdocs.pm/elixir/Kernel.html#struct/2 does.
Nicd
This is dangerous as it doesn’t check that the keys in map_defaults actually correspond to keys of the struct. You may end up with a broken struct which is annoying to debug. What you should do is:
s = struct!(User, map_defaults)
This will ensure that keys that are in @enforce_keys must be exist and there are no keys that don’t exist in the struct. Otherwise it will raise an error. There is also Kernel.struct/2 (i.e. without exlamation mark) that will just discard unknown keys and won’t enforce @enforce_keys.
mbuhot
Untested, but it seems like cast and apply_changes should do what you want:
%User{} |> Ecto.Changeset.cast(map, User.__schema__(:fields)) |> Ecto.Changeset.apply_changes()








