Unable to make JSONB work with Ecto model in Phoenix

I am trying to save JSON in a jsonb column in postgresql, I tried this tutorial and also started reading the Ecto API as well as Postgrex but cannot make it work, a working example will enlighten me :) So far I have added this to my configuration

config :bonsai, Bonsai.Repo,
  adapter: Ecto.Adapters.Postgres,
  username: "demo",
  password: "demo123",
  database: "bonsai_test",
  hostname: "localhost",
  pool: Ecto.Adapters.SQL.Sandbox,
  extensions: [{Postgrex.Extensions.JSON, [library: Poison]}]

This is my model

defmodule Bonsai.Organization do
  use Bonsai.Web, :model

  schema "organizations" do
    field :name, :string
    field :currency, :string
    field :tenant, :string
    field :info, Bonsai.Json.Type, default: %{}
    field :settings, :map, default: %{} #, :map#, Bonsai.Json.Type

    timestamps
  end

  @required_fields ~w(name currency tenant)
  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

And the type definition is in web/utils/json.ex

defmodule Bonsai.Json.Type do
  @behaviour Ecto.Type
  alias Bonsai.Json

  def type, do: :json

  def load({:ok, json}), do: {:ok, json}
  def load(value), do: load(Poison.decode(value))

  def dump(value), do: Poison.encode(value)
end

When I try to check, I can’t get the information or settings map

defmodule Bonsai.OrganizationTest do
  use Bonsai.ModelCase

  alias Bonsai.Organization

  @valid_attrs %{currency: "USD", name: "Home", tenant: "bonsai",
    settings: %{"last_save" => true},
    info: %{"address" => "Samaipata", "mobile" => "73732677", "age" => 40}
  }
  test "Store json data" do
    changeset = Organization.changeset(%Organization{}, @valid_attrs)
    {:ok, org} = Bonsai.Repo.insert(changeset)
    assert @valid_attrs.info() == org.info
  end
end
+4
source share
1 answer

I am not sure why it does not work for you, but:

make sure you have the latest version of postgresql, json newa support.

It works for me, maybe it helps.

  • def change do
    create table(:objects) do
     add :drawing, :jsonb
     timestamps
    end
    
  • json, :

     use .Web, :model
      schema "objects" do
       field :drawing, :map
       timestamps
      end
    
+6

All Articles