How to store array with Ecto using Postgres

Josh Petitt picture Josh Petitt · Oct 11, 2015 · Viewed 16.4k times · Source

I would like to store an array of floating point values with Ecto using Postgres. I'm using Ecto with the Phoenix Framework and Elixir.

How would I define my model and migration for this?

I haven't tried much, except searching the web, which didn't find anything useful :-(

I did try defining a model with a schema like this:

  schema "my_model" do
    field :my_array, :array

    timestamps
  end

which gave an error "invalid or unknown type :array for field :my_array"

Answer

Josh Petitt picture Josh Petitt · Oct 11, 2015

I found the answer in the list of primitive types for Ecto.Schema here:

Ecto.Schema

The answer is to define the type like this:

  schema "my_model" do
    field :my_array, {:array, :float}

    timestamps
  end