Search code examples
elixirphoenix-frameworkelixir-poison

Serializing many to one relation with Phoenix


I'm looking for some kind of tutorial/example of serializing structs into json with Poison lib in Phoenix app. I've found such example: https://robots.thoughtbot.com/building-a-phoenix-json-api but it's not using Poison and it isn't covering structs with nested map of structs. I've also tried this answer: https://stackoverflow.com/a/34751835/4409736 but I've failed to implement it properly. I want to serialize map of structs having has_many relation with another struct from my controller. Has anybody seen something like that or could help me with such a case?


Solution

  • You can use simply defimpl for Poison.Encoder protocol and implement custom encode. You will need to do it directly in model file and that way you can add additional fields or simply ensure that relation is properly loaded.

    For getting the relation items you can simply use private function with assoc/2 and then use it as a field in encode.