Adzz

Adzz

Ecto: Serialising a jsonb array column into a list of possible types

I have a jsonb array column in a (postgres) db. It is a list that can be only a limited number of maps, is there a way to represent this in Ecto?

I’ve tried implementing a custom Ecto Type, with cast functions that correctly figure out which struct to serialize / deserialize :

  schema "table_name" do
    embeds_many(:things, DB.Things)

    timestamps()
  end

Then in a custom type:

  def cast(thing) do
    case thing.type do
      :foo -> {:ok, Foo.new(thing)}
      _ -> :error
    end
  end

  def load(data) when is_map(data) do
    data =
      for {key, val} <- data do
        {String.to_existing_atom(key), val}
      end

    {:ok, struct!(Foo, data)}
  end

  def dump(thing = %Foo{}), do: {:ok, Map.from_struct(thing)}
  def dump(_), do: :error

But this doesn’t work as the last argument to the embeds_many needs to be an Ecto schema.

I know I can use embeds_many and give a schema for an array of ONE type of thing, but I want to be able to say “This can be an array of any of these types of things” and have those things be embeded schemas. An embeds_one_of

Most Liked

idi527

idi527

Can you make the thing into a wrapper struct like %Thing{inner: %Foo{}}?

  schema "table_name" do
    embeds_many(:things, Thing)

    timestamps()
  end
  def cast(%Think{inner: inner}) do
    inner
  end

  def load(data) when is_map(data) do
    data =
      for {key, val} <- data do
        {String.to_existing_atom(key), val}
      end

    {:ok, %Thing{inner: struct!(Foo, data)}}
  end

  def dump(%Think{inner: %Foo{} = foo} ), do: {:ok, Map.from_struct(foo)}
  def dump(_), do: :error

or something like that.

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
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
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
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
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
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
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
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

Other popular topics Top

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
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
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 49522 488
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
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
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
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
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

We're in Beta

About us Mission Statement