hudsonbay

hudsonbay

Protocol Jason.Encoder not implemented for {:ok, #Money<:USD, 20000>} of type Tuple, Jason.Encoder protocol must always be explicitly implemented

Hello, I have a very newbie question if anyone knows.

I’m using this libraries

{:ex_money, "~> 5.5.1"},
{:ex_money_sql, "~> 1.4.4"}

to deal with Money. First time I work with Money types because I was doing it using only decimals.

I configured this libraries well, I know because I can seed data with no problem using this:

Repo.insert!(%InnovationProject{
  budget: Money.new(:USD, 7800),
  term: 2
})

and receiving no errors at that time. And when doing GET requests the format is a Money type in the result.
So, with that out of the way, I have the following Ecto.Schema on Phoenix Framework:

schema "innovation_projects" do
    field :budget, Money.Ecto.Composite.Type
    field :term, :decimal
    field :anual_cost, Money.Ecto.Composite.Type, virtual: true

    timestamps()
  end

My changeset:

def changeset(innovation_project, attrs) do
    innovation_project
    |> cast(attrs, [
      :budget,
      :term
    ])
    |> validate_required([
      :budget,
      :term
    ])
    |> calculate_anual_cost()
  end

And calculate_anual_cost function looks like this:

 defp calculate_anual_cost(changeset) do
    budget = get_change(changeset, :budget)
    term = get_change(changeset, :term)

    changeset
    |> put_change(:anual_cost, budget |> Money.div(term))
  end

Now, I think that there’s no problem here. But my error comes when I want to show anual_cost on my views

So, my innovation_project_view.ex looks like this:

def render("innovation_project.json", %{innovation_project: innovation_project}) do
    %{
      budget: innovation_project.budget,
      term: innovation_project.term,
      anual_cost: innovation_project.anual_cost
    }
  end

Eyes on anual_cost: innovation_project.anual_cost because that’s the line giving me this issue:

protocol Jason.Encoder not implemented for {:ok, #Money<:USD, 20000>} of type Tuple, Jason.Encoder protocol must always be explicitly implemented. This protocol is implemented for the following type(s): Money, Cldr.LanguageTag, Ecto.Association.NotLoaded, Ecto.Schema.Metadata, BitString, List, Integer, Any, Date, Map, NaiveDateTime, Atom, Jason.Fragment, DateTime, Decimal, Time, Float

So, my view can show budget, which is a Money type but the generated virtual field anual_cost can’t be shown. How can I show my anual_cost?

One more thing:

iex> Money.div Money.new(:USD, 200), 2
    {:ok, Money.new(:USD, 100)} 

Thanks in advance

Marked As Solved

Nicd

Nicd

The Money.div function returns a tuple of {:ok, value} or {:error, reason}. So where you are using the function, you need to pick the value out of the tuple. Jason won’t encode tuples as JSON by default, so that’s what the error comes from.

So in your changeset function you should be doing maybe something like:

with {:ok, cost} <- Money.div(budget, term) do
  put_change(changeset, :anual_cost, cost)
else
  {:error,  reason} ->
    put_error(changeset, ... something something)
end

Btw annual is written with two n’s. :slight_smile:

Also Liked

hudsonbay

hudsonbay

HI, thank you very much. You are so right. I told you I was a newbie :slight_smile:

Also thanks for the typo clarification in annual :ok_hand: It made a lot of sense in Spanish to me :sweat_smile:

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Tee
can someone please explain to me how Enum.reduce works with maps
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
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
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
yawaramin
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function: -dialyzer...
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

Other popular topics Top

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
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31265 143
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52673 488
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement