Convert Map to JSON when saving to database?

Just to be thorough for future visitors, here’s the full example:

From my migration:

# ...
# (The :map type gets mapped to :jsonb for PostGres from what I understand)
add :meta, :map, default: "{}"  # <-- assuming I always want to store a JSON object

From my schema:

# ...
field :meta, :map, null: false, default: "{}"

And how it all works:

attrs = %{
    # ...
    meta: %{
        arbitrary: "stuff"
    }
}
result = %MyThing{}
  |> MyThing.changeset(attrs)
  |> Repo.insert()

  # result:
  %Auth.Schemas.AuthorityUser{
      __meta__: #Ecto.Schema.Metadata<:loaded,"my_thing">,
      # ...
      meta: %{
          "arbitrary" => "stuff",
      },
     # ...
  }
4 Likes