Postgres column type for embeds_many

Everywhere I’ve seen a blog post, etc. about making a column in postgres for an embeds_many, I see the same advice: use add :column, {:array, :map}, default: [] in the migration.

But this creates a postgres array of jsonb objects. This is not sensible to query on.

In my testing, I’ve found that simply using a :jsonb type for the column is sufficient and correct for everything embeds_many can do. It can leverage all the power of postgres’ jsonb type as well.

So here’s the question: If everyone is suggesting {:array, :map} and that seems to be inadequate for the purposes of doing standard database things, am I wrong for using :jsonb? Is there something about this that I’m overlooking?

3 Likes

I have exactly the same question, I spend a couple of hours on this since I noticed that with {:array, :map} the data is not stored as JSON but as a JSON string!

Seems that there is something mixed up. What I do know is that {:array, :map} is the adapter generic way of saying you want to store embedded records independent of the database you are using. For Postgres this should map to JSONB but apparently it does not or does in a strange way.

https://robots.thoughtbot.com/why-ecto-s-way-of-storing-embedded-lists-of-maps-makes-querying-hard

tldr: it’s suggested because of older postgres version support

2 Likes