39

I am going over the following tutorial in an attempt to get my head around elixir and phoenix:

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

I am running into an issue with the test, mainly using Poison.encode! on the Contact model. I get the following error:

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

This led me to the following issue:

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

I have added the code from the blog article into lib/poison_encoder.ex, but I now get the following error:

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

The code I have in 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
Dave Powers
  • 2,051
  • 2
  • 30
  • 34
Allister
  • 851
  • 3
  • 10
  • 21

1 Answers1

67

Update to Poison 1.5. With it you can declare in your models:

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

It is going to be faster, safer and cleaner.

José Valim
  • 50,409
  • 12
  • 130
  • 115
  • 18
    Can you please describe "it didn't work"? There are many reasons why it could happen so without a proper description, it is really hard to figure out what else should be done. – José Valim Sep 16 '15 at 08:20
  • 1
    I'd love to see more examples, demonstrating this. https://github.com/elixir-ecto/ecto/blob/master/lib/ecto/schema.ex#L53 > `@derive` - the same as `@derive` available in `Kernel.defstruct/1` as the schema defines a struct behind the scenes; – zeroasterisk Aug 09 '17 at 15:39
  • 1
    Note that this can be done with Jason as well ```@derive {Jason.Encoder, only: [:name, :other_field]}``` – Joris Kok Dec 13 '20 at 08:39
  • 1
    Is there a way to make it `camelCase` on encoding instead of `snake_case`? – kasvith Jun 11 '21 at 10:34