Elixir 如何序列化EXTO record结构,使其在数据库中可存储为:map?

Elixir 如何序列化EXTO record结构,使其在数据库中可存储为:map?,elixir,ecto,Elixir,Ecto,我想存储从Repo.get(MyModel,id)返回的exto.Schema结构 像\uuuu meta\uuuu,关联:之类的东西会阻止jsonification,所以我捕获了一个异常(这是合理的)。是否有任何exto本机函数仅获取记录列的映射,我可以将其序列化并存储在数据库中?由于我不知道任何用于此目的的exto本机函数,我想您应该使用: 筛选不需要的密钥: 并将结果设置为: 编辑:看起来您可以在查询中使用“map()”来返回映射,而不是结构:我的解决方案 defmodule MyA

我想存储从
Repo.get(MyModel,id)
返回的
exto.Schema
结构


\uuuu meta\uuuu
关联:
之类的东西会阻止jsonification,所以我捕获了一个异常(这是合理的)。是否有任何
exto
本机函数仅获取记录列的映射,我可以将其序列化并存储在数据库中?

由于我不知道任何用于此目的的exto本机函数,我想您应该使用:

筛选不需要的密钥:

并将结果设置为:

编辑:看起来您可以在查询中使用“map()”来返回映射,而不是结构:

我的解决方案

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
Elixir允许您派生协议实现:

我不确定您使用的是什么JSON解析器,但对于
Jason
,例如,您可以在他们的自述文件中找到以下内容:

If you need to encode some struct that does not implement the protocol, if you own the struct, you can derive the implementation specifying which fields should be encoded to JSON:

@derive {Jason.Encoder, only: [....]}
defstruct # ...

Finally, if you don't own the struct you want to encode to JSON, you may use Protocol.derive/3 placed outside of any module:

Protocol.derive(Jason.Encoder, NameOfTheStruct, only: [...])
Protocol.derive(Jason.Encoder, NameOfTheStruct)
还不如展示一下如何使用毒药:

When deriving structs for encoding, it is possible to select or exclude specific attributes. This is achieved by deriving Poison.Encoder with the :only or :except options set:

defmodule PersonOnlyName do
  @derive {Poison.Encoder, only: [:name]}
  defstruct [:name, :age]
end

defmodule PersonWithoutName do
  @derive {Poison.Encoder, except: [:name]}
  defstruct [:name, :age]
end
In case both :only and :except keys are defined, the :except option is ignored.