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?