johnnyicon

johnnyicon

How do I use the Postgres JSONB / Postgrex JSON extension?

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: https://github.com/elixir-ecto/postgrex/blob/master/lib/postgrex/extensions/json.ex

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

Thanks for the help in advance! :slight_smile:

Marked As Solved

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

Also Liked

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?

Where Next?

Popular in Questions Top

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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
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
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
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
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
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 Postg...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
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
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
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
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New

We're in Beta

About us Mission Statement