如何序列化 Ecto 记录结构以使其可作为 :map 存储在数据库中?

asi*_*niy 2 elixir ecto

我想存储一个Ecto.SchemaRepo.get(MyModel, id).

诸如__meta__,association: <Association is not loaded>防止对它进行 jsonifying 之类的东西,所以我捕获了一个异常(这是合理的)。是否有任何Ecto本机函数可以仅获取我可以序列化并存储在数据库中的记录列的映射?

asi*_*niy 6

我的解决方案

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
Run Code Online (Sandbox Code Playgroud)