无法在使用 Ecto 迁移时为字符串数组列(长生不老药列表)创建默认值

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

我正在处理一个 phoenix 1.3 项目(使用默认的 postgres 数据库),我正在尝试添加一个字符串数组列,其默认值为填充列表。

这是迁移:

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

当我 运行 迁移时,出现以下错误:

** (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(...)

使用 {:array, input_type}.

时,似乎除了默认的空列表外不可能有任何其他内容

我尝试用默认设置做的事情实际上是一种 hack,还有更好的方法吗?或者,如果我正在尝试做的是首选方法,是否有我可以用来做同样事情的技巧?感谢任何帮助。

我不确定为什么 Ecto 默认仅支持空数组,但您现在可以使用 fragment 并在 PostgreSQL 语法中指定数组:

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

添加了对空数组的支持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