How to store array with Ecto using Postgres
20,303
Solution 1
I found the answer in the list of primitive types for Ecto.Schema here:
The answer is to define the type like this:
schema "my_model" do
field :my_array, {:array, :float}
timestamps
end
Solution 2
As Josh wrote use the array type from Ecto.Schema
In the model:
schema "my_model" do
field :my_array, {:array, inner_type}
end
@neildaemond Migration:
alter table(:my_models) do
add :my_array, {:array, inner_type}
end
Replace inner_type
with one of the valid types, such as :string
.
You can also do the same thing with a map
type:
schema "my_model" do
field :my_map, {:map, inner_type}
end
Comments
-
Josh Petitt almost 4 years
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"
-
neildaemond over 7 yearsThanks, how would you write the migration for that?
-
pmarreck over 6 yearsAny idea how to properly construct a form that would let someone input the elements of this array or map?
-
Bartłomiej Skwira over 6 years@pmarreck have you looked at Form docs? hexdocs.pm/phoenix_html/Phoenix.HTML.Form.html I usually work on an API apps so I don't use forms and can't help
-
pmarreck over 6 yearsI have, don't see anything helpful there in this case
-
Sash about 6 yearsHere is a generator example:
mix phx.gen.schema Blog.Post blog_posts tags:array:string
-
xji almost 6 years@pmarreck This post seems to be relevant.
-
wodow over 3 yearsThe example from @sash generates a migration with the relevant line
add :tags, {:array, :string}