Can't create default for string array column (elixir list) in migration with Ecto
Asked Answered
E

1

10

I'm working on a phoenix 1.3 project (using the default postgres database) and I'm trying to add a string array column with a default value of a populated list.

Here's the migration:

defmodule DfyDashboard.Repo.Migrations.AddLeadSourceToOffice do
  use Ecto.Migration

  def change do
    alter table(:offices) do
      add :lead_sources, {:array, :string}, default: [
        "Event",
        "Facebook",
        "Google/Online",
      ]
    end
  end
end

When I run the migration, I get the following error:

** (ArgumentError) unknown default ["Event", "Facebook", "Google/Online"] for type {:array, :string}. :default may be astring, number, boolean, empty list, map (when type is Map), or a fragment(...)

It seems like it isn't possible to have anything but an empty list for a default when using {:array, input_type}.

Is what I'm trying to do with the default actually a hack and there's a better way to do it? Or if what I'm trying to do is the preferred method, is there a hack I can use to do the same thing? Any help is appreciated.

Eatables answered 23/2, 2018 at 15:22 Comment(0)
R
13

I'm not sure why Ecto only supports empty arrays as default but you can use fragment for now and specify the array in PostgreSQL syntax:

add :lead_sources, {:array, :string},
  default: fragment("ARRAY['Event', 'Facebook', 'Google/Online']")

Support for empty arrays was added in 2015 but not non-empty arrays. I think they would be open to adding this feature. You might want to ask the core devs on their mailing list.

Rufford answered 23/2, 2018 at 15:32 Comment(2)
Awesome, I hadn't come across fragments before, that worked great! Thanks for the tip on the mailing list, I'll do that.Eatables
very nice I was looking for a way to achieve this tooTanana

© 2022 - 2024 — McMap. All rights reserved.