I want to store an Ecto.Schema
struct which is returned from Repo.get(MyModel, id)
.
Stuff like __meta__
, association: <Association is not loaded>
prevents from jsonifying it, so I catch an exception (it's reasonable). Is there any Ecto
native function to get only map of record columns which I can serialize & store at the database?
My solution
defmodule MyApp.Schema do
@schema_meta_fields [:__meta__]
def to_storeable_map(struct) do
association_fields = struct.__struct__.__schema__(:associations)
waste_fields = association_fields ++ @schema_meta_fields
struct |> Map.from_struct |> Map.drop(waste_fields)
end
end