Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 749
DamonJanis Avatar asked Feb 23 '18 15:02

DamonJanis


1 Answers

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.

like image 194
Dogbert Avatar answered Oct 19 '22 03:10

Dogbert