【问题标题】:Ecto Changeset Array Type Returns "is invalid" ErrorEcto Changeset 数组类型返回“无效”错误
【发布时间】:2016-10-21 04:35:37
【问题描述】:

我正在尝试将列表插入到类型为 {: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"],
  ...
}

我猜我错过了一些基本的东西,但无法弄清楚。任何帮助表示赞赏!如果您需要更多代码,请告诉我。

【问题讨论】:

  • 您能告诉我们您是如何调用changeset 函数(两个参数的值)的吗?
  • 我的错,我不小心漏掉了控制器部分。

标签: elixir phoenix-framework ecto


【解决方案1】:

问题是您首先将一个字符串作为images 传递给Article.changeset/2,这将images 标记为无效,然后稍后使用Ecto.Changeset.change/2 输入一个有效值,但Ecto.Changeset.change/2 不会重新运行自动验证。对于您的示例,您可以简单地将正确的images 值传递给Article.changeset/2

images = String.split(images, ",", trim: true)
changeset = Article.changeset(%Article{}, %{article_params | "images" => images)

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2019-12-12
    相关资源
    最近更新 更多