thijsvtol

thijsvtol

Jason.Encoder not implemented phoenix

I’m currently using a model button that referended is to another list of objects called items
When I make a POST call to the service it returns the following error message:

[error] #PID<0.440.0> running BuyButtonServiceWeb.Endpoint (connection #PID<0.430.0>, stream id 3) terminated
Server: localhost:4000 (http)
Request: POST /button
** (exit) an exception was raised:
    ** (Protocol.UndefinedError) protocol Jason.Encoder not implemented for %BuyButtonService.Dashboard.Item{__meta__: #Ecto.Schema.Metadata<:loaded, "items">, button: #Ecto.Association.NotLoaded<association :button is not loaded>, buttonId: 1, button_id: nil, id: 1, ingredient: "string", inserted_at: ~U[2021-01-20 14:52:19Z], productId: 0, quantity: 0, updated_at: ~U[2021-01-20 14:52:19Z]} of type BuyButtonService.Dashboard.Item (a struct), Jason.Encoder protocol must always be explicitly implemented.

If you own the struct, you can derive the implementation specifying which fields should be encoded to JSON:

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

My controller:

def create(conn, %{"button" => button_params}) do
    with {:ok, %Button{} = button} <- Dashboard.create_button(button_params) do
      conn
      |> put_status(:created)
      |> put_resp_header("location", Routes.button_path(conn, :show, button))
      |> render("show.json", button: button)
    end
  end

Button model:

defmodule BuyButtonService.Dashboard.Button do
  use Ecto.Schema
  import Ecto.Changeset
  alias BuyButtonService.Dashboard.Item, as: Item

  @derive Jason.Encoder
  schema "button" do
    has_many :items, {"items", Item}, foreign_key: :buttonId
    field :name, :string
    field :userId, :integer

    timestamps([type: :utc_datetime])
  end

  @doc false
  def changeset(button, attrs) do
    button
    |> cast(attrs, [:userId, :name])
    |> cast_assoc(:items, with: &Item.changeset/2)
    |> validate_required([:userId, :name, :items])
  end
end

Items model:

defmodule BuyButtonService.Dashboard.Item do
  use Ecto.Schema
  import Ecto.Changeset
  alias BuyButtonService.Dashboard.Button, as: Button

  schema "items" do
    field :buttonId, :integer
    belongs_to :button, Button
    field :ingredient, :string
    field :productId, :integer
    field :quantity, :integer

    timestamps([type: :utc_datetime])
  end

  @doc false
  def changeset(item, attrs) do
    item
    |> cast(attrs, [:buttonId, :ingredient, :productId, :quantity])
    |> validate_required([:ingredient])
  end
end

When using the @derive {Jason.Encoder, only: [....]} it says that there can only be 1 destruct
Can someone tell me how to handle this or have another solution?

Marked As Solved

al2o3cr

al2o3cr

Can you post the code that triggers that error? schema uses defstruct as part of its implementation, so you’ll get a similar-sounding error if you write:

defstruct [:some_fields]
schema "items" do # <---- will try to defstruct as well

Side note:

  field :buttonId, :integer
  belongs_to :button, Button

This is likely not what you want - unless your table has both a buttonId and button_id column :thinking:

belongs_to will call field with the value it’s given for foreign_key (or by adding _id on the end of the name if that’s not supplied)

Also Liked

John-Goff

John-Goff

If you read the stack trace, you can see that the first error it shows is this

** (Protocol.UndefinedError) protocol Enumerable not implemented for #Ecto.Association.NotLoaded<association :items is not loaded> of type Ecto.Association.NotLoaded (a struct) 

What this error is telling you is that you have fetched a button that has_many items, but you have not fetched the items. The Ecto.Association.NotLoaded struct is the default value if you have not preloaded your associations. To fix this you need to add a preload to your query or somewhere else before your view.

Where Next?

Popular in Questions Top

Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;%= ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
New

Other popular topics Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43806 214
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement