johnnyicon

johnnyicon

Hi all,

I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage.

I’m trying to use Postgres’ JSONB via the :map datatype.

Here’s my migration to add it to my table:

defmodule MyApp.Repo.Migrations.AddMapFieldToUser do
  use Ecto.Migration

  def change do
    alter table(:users) do
      add :data, :map
    end
  end
end

Here’s my schema:

defmodule MyApp.User do
  use MyApp.Web, :model
  use Coherence.Schema

  schema "users" do
    field :first_name, :string
    field :last_name, :string
    field :email, :string
    field :data, :map

    coherence_schema()

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:first_name, :last_name, :email] ++ coherence_fields)
    |> unique_constraint(:email)
    |> validate_required([:first_name, :last_name, :email])
    |> validate_coherence(params)
  end
end

I’ve been trying to set values into the data map using a changeset, but I haven’t had any luck. I’ve tried using both a JSON string and a map.

JSON string:

changeset = User.changeset(retrieved_user, %{data: "{test:'awesome'}"})
#Ecto.Changeset<action: nil, changes: %{}, errors: [],
 data: #MyApp.User<>, valid?: true>

Map:

changeset = User.changeset(john, %{data: %{test: "awesome"}})
#Ecto.Changeset<action: nil, changes: %{}, errors: [],
 data: #PodioBackup.User<>, valid?: true>

You’ll see that the changes map is empty.

Which leads me to believe that I am clearly missing something! :sweat_smile: And I’m thinking maybe I need to add this JSON extension that many websites are referring to: postgrex/lib/postgrex/extensions/json.ex at master · elixir-ecto/postgrex · GitHub

How do I actually use that JSON extension? And, what am I doing wrong?

Thanks for the help in advance! :slight_smile:

Showing Posts 1 to 9

alexgaribay

alexgaribay

Phoenix Core Team

You’re missing a cast of :data in your changeset.

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:first_name, :last_name, :data] ++ coherence_fields)
    |> ...
  end
johnnyicon

johnnyicon OP

Somehow I knew it was going to be something like that.

Thanks @alexgaribay. That was it!

nezzart

nezzart

In this

shouldn’t the “data” be of type “jsonb” instead of “map”?

BrightEyesDavid

BrightEyesDavid

The first argument (:data) in add :data, :map is the name of the table column. The type is the second argument (:map).

Here’s the documentation for Ecto.Migration.add.

nezzart

nezzart

yes, but my question is about “map” vs “jsonb”

david, your eyes are soooo green!

michalmuskala

michalmuskala

They are equivalent when using postgres. map is an abstract type and each database adapter can choose the actual representation - for postgres it’s jsonb.

Qqwy

Qqwy

TypeCheck Core Team

So is a correct conclusion that using :map would be preferable over using :json, to allow you to switch database adapters, if desired, later on?

SoldierCoder

SoldierCoder

Is such a thought falling into this famous trap: “Premature optimization is the root of all evil!”? Or to put this another way, do you want your code to express what you are intending to happen right now? Or do you want your code to express what you MIGHT want it to do in the somewhat nebulous FUTURE?

“Why should you want to know?
Don’t you mind about the future
Don’t you try to think ahead
Save tomorrow for tomorrow
Think about today instead” – Jesus

Qqwy

Qqwy

TypeCheck Core Team

No, I don’t think this is a case of premature optimization. Though I will admit that I don’t know exactly what my thoughts were when I wrote the last post in this topic in 2017, 8 years ago.

I would still consider that programming is a challenge of solving puzzles with often incomplete information. Doing as little optimization (regardless of what you’re optimizing for) as needed while keeping your project as flexible as possible for the future (within practical limits) is therefore often a great approach because you can make better choices in the future as you will have (more) complete information then.

In this case: it costs nothing (not in performance, not in memory and not in developer mental complexity) to use :map instead of :jsonb if you want to store a hashmap with string keys in a Postgres column, whereas it does allow you to more easily switch over to a different database engine.

I think that that can be considered roughly the opposite of premature optimization, especially of the kind that Dijkstra originally talked about.

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews