Search code examples
jsonelixirecto

Return all fields in Ecto query as a map for sending results back as json?


If I don't put a select, ecto returns the full struct which makes sense but then I have to convert to a map and remove the __meta__ field.

from x in __MODULE__ will return list of %MODULE{__meta__: #Ecto.Schema.Metadata...,id: 1, name: "bob"}

Is there a better solution than listing it out in the select clause like this: from x in __MODULE__, select: %{x.id: id, x.name: name...}

And if not, is there a way to dynamically generate this select clause off of the schema?


Solution

  • While I don’t see any issue with calling Map.from_struct/1, the proper approach would be to implement json encoder for the structure in question. Then you’ll be able to serialize the struct itself whenever you wish.

    For Jason it’s fairly straightforward with @derive:

    defmodule MySchema do
      @derive Jason.Encoder
    
      schema ...
    end