Created
April 12, 2022 08:51
-
-
Save hoangbits/c334d1d890e1258d566d9968b4090d02 to your computer and use it in GitHub Desktop.
implicit encode Ecto schema with Jason
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# inside an ecto Schema, adding this: | |
defimpl Jason.Encoder, for: [__MODULE__] do | |
def encode(struct, opts) do | |
Enum.reduce(Map.from_struct(struct), %{}, fn | |
({k, %Ecto.Association.NotLoaded{}}, acc) -> acc | |
({k, v}, acc) -> Map.reject(acc, fn {k, v} -> k === :__meta__ end) |> Map.put(k, v) | |
end) | |
|> Jason.Encode.map(opts) | |
end | |
end | |
# suggestion from: https://elixirforum.com/t/how-to-encode-ecto-schema-with-jason-with-all-fields/17221/2 | |
# Notice: I leave it here for testing only. It might be better to use Phoenix view to EXPLICITLY render json. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment