Ecto Changeset数组类型返回"无效"错误

时间:2016-10-20 20:16:49

标签: elixir phoenix-framework ecto

我试图将列表插入到类型为{:array, :string}的字段中,但是继续接收"无效"表单提交后出错。这是我的相关代码:

移植

def change do
  alter table(:articles) do
    add :images, {:array, :string}
  end
end

模型

schema "articles" do
  ...
  field :images, {:array, :string}
  ...
end

@required_fields ~w(title content user_id)
@optional_fields ~w(images)

def changeset(model, params \\ :empty) do
  model
  |> cast(params, @required_fields, @optional_fields)
  |> validate_length(:title, max: 78)
  |> strip_unsafe_content(params)
end
...

控制器

def create(conn, %{"article" => %{"images" => nil} = article_params}) do
  changeset = Article.changeset(%Article{}, article_params)

  case Repo.insert(changeset) do
    {:ok, article} ->
      conn
      |> put_flash(:info, "Article created successfully.")
      |> redirect(to: article_path(conn, :show, article))
    {:error, changeset} ->
      render(conn, "new.html", changeset: changeset)
  end
end

def create(conn, %{"article" => %{"images" => images} = article_params}) do
  images = String.split(images, ",", trim: true)
  changeset = Article.changeset(%Article{}, article_params)
              |> Ecto.Changeset.change(images: images)

  case Repo.insert(changeset) do
    {:ok, article} ->
      conn
      |> put_flash(:info, "Article created successfully.")
      |> redirect(to: article_path(conn, :show, article))
    {:error, changeset} ->
      render(conn, "new.html", changeset: changeset)
  end
end

变更集

%Ecto.Changeset{action: :insert,
  changes: %{content: "\tTest",
    images: ["images/articles/hh_2016/1.jpg", "images/articles/hh_2016/2.jpg",
    "images/articles/hh_2016/3.jpg", "images/articles/hh_2016/4.jpg",
    "images/articles/hh_2016/5.jpg", "images/articles/hh_2016/6.jpg",
    "images/articles/hh_2016/7.jpg", "images/articles/hh_2016/8.jpg"],
    title: "Test", user_id: 31}, 
  constraints: [], 
  errors: [images: "is invalid"],
  ...
}

我猜测我错过了一些基本但却无法解决的问题。任何帮助表示赞赏!如果您需要更多代码,请与我们联系。

1 个答案:

答案 0 :(得分:1)

问题是您首先将字符串images传递给Article.changeset/2,这会将images标记为无效,然后在{{1 }},但Ecto.Changeset.change/2不会自动重新运行验证。对于您的示例,您只需将正确的Ecto.Changeset.change/2值传递给images

即可
Article.changeset/2