Skip to content

Instantly share code, notes, and snippets.

@edersohe
Last active February 8, 2020 15:43
Show Gist options
  • Save edersohe/7adc4d56da26b26cad05db2e2d8c1820 to your computer and use it in GitHub Desktop.
Save edersohe/7adc4d56da26b26cad05db2e2d8c1820 to your computer and use it in GitHub Desktop.
Ecto field convert a map to text and text to map [elixir :map -> postgres :text -> elixir :map]
# Into ecto migration "add :my_field, :text"
# Into ecto schema "field :my_field, MapToText"
defmodule MapToText do
use Ecto.Type
def type, do: :map
def cast(data) when is_map(data), do: {:ok, data}
def cast(_), do: :error
def load(data) when is_binary(data), do: Jason.decode(data)
def load(_), do: :error
def dump(data) when is_map(data), do: Jason.encode(data)
def dump(_), do: :error
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment