Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get PostgreSQL hashes in Phoenix's Ecto models?

I want to define a PostgreSQL-Hash type field in my Ecto model but I'm not sure how to do it. I haven't found an explicit guide on this topic and I'm assuming it's somewhere hidden in here: http://hexdocs.pm/ecto/Ecto.Schema.html

Has anyone the definite guide to do PostgreSQL-Hash fields in Ecto?

like image 269
Philip Claren Avatar asked Oct 16 '15 09:10

Philip Claren


1 Answers

As JustMichael stated, the answer is the :map type.

The table definition:

CREATE TABLE public.authors (
  id INTEGER PRIMARY KEY NOT NULL DEFAULT nextval('authors_id_seq'::regclass),
  settings HSTORE,
  updated_at TIMESTAMP WITHOUT TIME ZONE,
  inserted_at TIMESTAMP WITHOUT TIME ZONE
);

The Ecto model:

defmodule Nexus.Author do
  use Nexus.Web, :model

  schema "authors" do
    field :settings, :map
    timestamps
  end
end

Now I can get access the settings Nexus.Repo.get(Author, some_id).settings and get a map in return.

like image 141
Philip Claren Avatar answered Oct 15 '22 06:10

Philip Claren