krut

krut

Using custom type in embedded schema

I am writing an API integration that uses embedded schemas to cast response data before it is used internally. The id fields in the responses are typically integers, and I would like them to convert them to strings.

I could transform these values manually, but there are a number of different responses and schemas, all with the same id format, so I am thinking it could be nice to define a custom type that handles this conversion “behind the scenes”.

I have defined my type as:

defmodule Types.ResponseID do
  @behaviour Ecto.Type
 
  def type, do: :string

  def cast(integer) when is_integer(integer) do
    { :ok, Integer.to_string(integer) }
  end

  def cast(string) when is_binary(string), do: { :ok, string }

  def cast(_), do: :error
end

And my schema:

defmodule Thing do
  use Ecto.Schema

  import Ecto.Changeset

  @primary_key false

  embedded_schema do
    field :id, Types.ResponseID
  end

  def from_response(data) do
    %__MODULE__{}
    |> Ecto.Changeset.cast(data, [:id])
    |> apply_changes()
  end

Which then throws these warnings:

warning: function dump/1 required by behaviour Ecto.Type is not implemented (in module ResponseID)
  lib/types/response_id.ex:1: ResponseID (module)

warning: function embed_as/1 required by behaviour Ecto.Type is not implemented (in module ResponseID)
  lib/types/response_id.ex:1: ResponseID (module)

warning: function equal?/2 required by behaviour Ecto.Type is not implemented (in module ResponseID)
  lib/types/response_id.ex:1: ResponseID (module)

warning: function load/1 required by behaviour Ecto.Type is not implemented (in module ResponseID)
  lib/types/response_id.ex:1: ResponseID (module)

My question - Do I need to add @behaviour Ecto.Type for a custom type in an embedded schema? Or is this a better way to define a custom type for this use case?

I found this comment suggesting that the additional behaviors (e.g. load/dump) are not necessary for custom types in embedded schemas, but I haven’t found any documentation showing an example of how to implement:

Thanks!

Marked As Solved

LostKobrakai

LostKobrakai

The callbacks are still required for the behaviour to be correctly implemented, otherwise you’ll get the warnings you see. They’re just not used for fields in embedded schemas.

Given you also have warnings about :embed_as and :equal? you’ll want to implement those as well or use use Ecto.Type instead of @behaviour Ecto.Type to have defaults generated.

Also Liked

Aetherus

Aetherus

In Ecto 3.x, you can implement embed_as/1 and return :dump. If you do so, Ecto will call YourCustomType.dump/1 before JSON serialization when saving embedded schema into DB. On the other hand, if embed_as/1 returns :self, then Ecto won’t call dump before JSON serializing an embed.

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
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
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
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
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
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
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
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
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
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

We're in Beta

About us Mission Statement