在长生不老药中将 Ecto 模型编码为 JSON

Encoding a Ecto Model to JSON in elixir

我正在阅读以下教程,试图了解 elixir 和 phoenix:

https://thoughtbot.com/blog/testing-a-phoenix-elixir-json-api

我 运行 遇到了测试问题,主要使用 Poison.encode!在接触模型上。我收到以下错误:

unable to encode value: {nil, "contacts"}

这导致我遇到以下问题:

https://github.com/elixir-lang/ecto/issues/840 和修复: https://coderwall.com/p/fhsehq/fix-encoding-issue-with-ecto-and-poison

我已将博客文章中的代码添加到 lib/poison_encoder.ex 中,但现在出现以下错误:

no function clause matching in Poison.Encoder.Any.encode/2

我在 lib/poison_encoder.ex:

中的代码
defimpl Poison.Encoder, for: Any do
  def encode(%{__struct__: _} = struct, options) do
    map = struct
          |> Map.from_struct
          |> sanitize_map
    Poison.Encoder.Map.encode(map, options)
  end

  defp sanitize_map(map) do
    Map.drop(map, [:__meta__, :__struct__])
  end
end

更新到 Poison 1.5。有了它,你可以在你的模型中声明:

@derive {Poison.Encoder, only: [:foo, :bar, :baz]}
schema "your schema" do
  field :foo
  field :bar
  field :baz
end

它会更快、更安全、更清洁。